Reversing a linked list
Turn every link of the list around one by one with three pointers, prev, cur and nxt; in one pass with no extra memory.
Walk the list from the start and turn each node's link back to the previous node. Three pointers are needed:
Read the full explanation ↓- Time:
O(n) - Space:
O(1) - Horowitz–Sahni, chapter 4
1 → 2 → 3 → 4 → 5 becomes 5 → 4 → 3 → 2 → 1.
class Node:def __init__(self, val):self.val = valself.next = Nonedef reverse_list(items):head = Nonefor x in reversed(items):node = Node(x)node.next = headhead = node# prev: the part already reversed; cur: the part still to do.prev, cur = None, headwhile cur is not None:nxt = cur.nextcur.next = prevprev = curcur = nxthead = prevout = []while head is not None:out.append(head.val)head = head.nextreturn out
Start
prevnull
curnull
Local variables
Orange = changed in this step
items list
12345
Call stack
- reverse_list()line 7
Step 1 of 84
Explanation
The idea
Walk the list from the start and turn each node's link back to the previous node. Three pointers are needed:
prev: the head of the part reversed so far,cur: the node whose link turns now,nxt: the next node, which must be saved before the link turns, or the rest of the list is lost.
At the end prev heads the reversed list.
Cost
One pass and a few pointers: O(n) time and O(1) memory. No node is copied or moved.
What to watch in the trace
- Two lists are drawn: from
prev(the reversed part) and fromcur(the part left); each step moves one node from the second to the first.