Все, что я сделал, это добавил распечатки в конце, чтобы посмотреть, что и где.Мне кажется, что ваш код делает то, что вы от него ожидаете.После функции reverse()
голова явно указывает на d
вместо a
class Node:
def __init__(self, data, prev=None, nxt=None):
self.val = data
self.prev = prev
self.next = nxt
class DoublyLinkedList:
def __init__(self, head):
self.head = head
def print_list(self):
cur = self.head
while cur is not None:
print(cur.val)
cur = cur.next
def reverse(self):
if self.head is None or self.head.next is None: return
cur = self.head
def reverse_node(node):
if node is None: return node
node.next, node.prev = node.prev, node.next
if node.prev is None: return node
return reverse_node(node.prev)
self.head = reverse_node(cur)
a = Node(1, prev=None)
b = Node(2, prev=a)
c = Node(3, prev=b)
d = Node(4, prev=c)
a.next = b
b.next = c
c.next = d
dll = DoublyLinkedList(a)
print("Head: ",dll.head.val)
dll.print_list()
dll.reverse()
print()
print("Head: ",dll.head.val)
dll.print_list()
print("Is the head at a? ",dll.head is a)
print("Is the head at d? ",dll.head is d)
ВЫХОД:
Head: 1
1
2
3
4
Head: 4
4
3
2
1
Is the head at a? False
Is the head at d? True