Linked List
Nodes that point to the next one: rewire pointers carefully, and use fast & slow pointers to find middles and cycles.
Spot it
Signals in the questionThe input is a ListNode chain (no index access).
Reverse, reorder, merge or remove in place.
Find a middle, a cycle or the nth from the end: fast & slow pointers.
The idea
O(n) time · O(1) spaceTo reverse, walk the list once and point each node back at the previous one. Save the next node before you rewire, or you lose the rest of the list.
Template · Reverse in place
1def reverse_list(head):2 prev = None3 while head:4 nxt = head.next # save the rest5 head.next = prev # point back6 prev, head = head, nxt7 return prev
The template, filled in for Reverse Linked List. The highlighted lines are the part every problem of this kind shares.
The best, free
One of eachPractice set
Loading your mission…
Common mistakes
1Rewiring next before saving it, losing the rest of the list.
2Returning the old head instead of the new one (prev).
3Not handling the empty list or a single node.
Check yourself
Question 1 of 2How do you find the middle of a linked list in one pass?