双向链表的反向实现是如何工作的?

How does implementation of reverse of doubly linked list work?

Python中双向链表的反向实现是如何实现的?具体来说 current = current.prev and head=temp.prev

def reverse(head):
    temp = None
    current = head 
        
    
    while current is not None: 
        temp = current.prev  
        current.prev = current.next
        current.next = temp 
        current = current.prev 

    
    if temp is not None: 
        head = temp.prev 
    return head

取一个双向链表: [1] <-> [2] <-> [3]

 head = 1
 temp = None
 current = head = 1

 while current is not None:
     # loop 1, current = 1
     temp = head.prev = None
     current.prev = current.next = 2
     current.next = temp = None
     current = current.next = 2
     # This now looks like this
     # [2] <- [1] -> None 
     # loop 2, current = 2
     temp = current.prev = 1
     current.prev = current.next = 3
     current.next = temp = 1
     current = current.next = 3
     # Now we have
     # [3] <- [2] <-> [1] -> None
     # Last time: 
     temp = current.prev = 2
     current.prev = current.next = None
     current.next = temp = 2
     current = current.next = None
     # [3] <-> [2] <-> [1]
     # break out of loop

          
# I think this should be while temp is not None
if temp is not None:
    temp = 2
    head = temp.prev = 3

return head

这是反转双向链表所需要的:

def reverse(head):
    curr = head
    while True:
        # Swap previous and next pointers
        curr.prev, curr.next = curr.next, curr.prev
        if curr.prev is None:  # Last node
            head = curr
            break

        curr = curr.prev

    return head

完全实现 input/output:

class DLLNode(object):
    def __init__(self, data):
        self.next = None
        self.data = data
        self.prev = None


def reverse(head):
    curr = head
    while True:
        curr.prev, curr.next = curr.next, curr.prev
        if curr.prev is None:
            head = curr
            break

        curr = curr.prev

    return head


def _print(head):
    while head.next is not None:
        print('{}<->'.format(head.data), end='')
        head = head.next
    print('{}'.format(head.data))


inputs = list(map(int, input().strip().split()))
head = None
for value in inputs:
    new_node = DLLNode(value)
    if head is None:
        head = new_node
        curr = head
        continue

    curr.next = new_node
    new_node.prev = curr
    curr = new_node
print('Before reverse:', end=' ')
_print(head)
print('After reverse:', end=' ')
_print(reverse(head))

输入:

1 2 3 4 5

输出:

Before reverse: 1<->2<->3<->4<->5
After reverse: 5<->4<->3<->2<->1