Reversing a linked list in Python, visualized step by step
PythonC
Walk from the head to the tail and point each node's next back at the node before it. Save the next node first: once a pointer is changed, the rest of the list would be lost.
reverse_linked_list.py
class Node:
def __init__(self, val, next=None):
self.val = val
self.next = next
head = Node(1, Node(2, Node(3, Node(4))))
prev = None
cur = head
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
head = prev
while head:
print(head.val, end=" ")
head = head.next
print()
How Reverse a linked list works
- prev starts empty; cur points at the head.
- Save the node after cur (next).
- Point cur's next at prev: this node now faces back.
- Move prev and cur one step forward; when cur is empty, prev is the new head.
What to watch
The arrowsEach step turns one node's arrow from right to left.
nextIt holds on to the part not reversed yet; without it the list breaks.
FAQ
What is the time complexity of reversing a linked list?
O(n): each node is visited once. Only a few pointers are used, so the extra space is O(1).
What is the most common mistake?
Changing cur's next before saving the next node: by then it points backwards, and the rest of the list is gone. Save next first.
Can it be done recursively?
Yes, but recursion uses O(n) stack and can overflow on a long list. Interviews usually expect both.