I'm trying to write a simple function that reverses a linked list in Python:
def reverse(head):
prev = None
nxt = head.next
head.next = prev
while nxt:
prev = head
head = nxt
head.next = prev
nxt = nxt.next
return head
The logic seemed fine when I thought through it.: First move prev to head, then shuffle head forward so it points to the same node as nxt, before setting head.next to where it was. Finally moving nxt forward by one. Iterate until nxt reaches the end of the list.
However when I tried to reverse a linked list 0->1->2->3->4->5 with the following code:
def traverse(head):
while head:
print(head.val)
head = head.next
it repeatedly printed 0 and 1 endlessly.