Linked list techniques: reverse, middle, merge, detect a cycle
Four classic list moves: reverse by rewiring pointers, find the middle and detect cycles with slow and fast runners, and merge two sorted lists.
Reverse a list and merge two sorted lists
The idea
Every arrow in a singly linked list points one way. B knows C but has no idea where A is.
Reversing the list and merging two lists both come down to rewiring arrows while you can only see one node ahead.
Intuition
Three pointers do the work. cur's arrow turns to prev, and nxt keeps hold of the rest.
Once cur.next points back at prev, the only link to node 3 is gone. Saving it in nxt first keeps the rest reachable.
To merge two sorted lists, compare the two heads. The smaller one goes next in the result.
Complexity
Reversal visits each node once: O(n) time. It keeps three pointers, so extra space is O(1).
Copying the values into an array and rebuilding would also be O(n) time, but it needs O(n) extra memory.
Merging attaches each of the n + m nodes once: O(n + m) time. It relinks the nodes, so extra space is O(1).
Pitfalls
Flip cur.next before saving it and the rest of the list is lost. Always save nxt first.
A node is reachable only through some arrow or pointer. After 2 points back to 1, nothing points to 3.
After the loop, head still names the old first node, now the tail. Return prev instead.
Variations
Merge sort on a list splits it at the middle, sorts each half, then merges the halves with this merge.
Recursion can reverse too: reverse the rest, then point the next node back at this one.
Slow and fast runners: middle node and cycle detection
The idea
On a circular track a fast runner always laps a slow one. On a straight road the fast one just finishes first.
Two pointers moving at different speeds tell you about the shape of a list without storing anything.
Intuition
fast moves two nodes per step, slow moves one. When fast reaches the end, slow is half way.
If the list loops, fast never reaches null. It gains one node per step and lands on slow.
Inside the loop the gap between them shrinks by exactly one each step, so fast cannot jump over slow.
Complexity
Both runs take O(n) steps and store two pointers. A set of visited nodes also finds a loop, but uses O(n) memory.
slow enters the loop within n steps. After that fast closes the gap by one per step, so they meet within one more lap.
Pitfalls
Check fast and fast.next before jumping. Reading fast.next.next on the tail crashes.
Variations
After the meeting, start p at the head and move p and slow one node each. They meet where the loop starts.
Palindrome check: find the middle, reverse the second half, then compare the halves pair by pair. Here 1 = 1 and 2 = 2.
Code
Pseudocode
prev ← null, cur ← head
while cur ≠ null
nxt ← cur.next
cur.next ← prev
prev ← cur
cur ← nxt
return prev
Python
def reverse_list(head):
prev, cur = None, head
while cur is not None:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return prev
JavaScript
function reverseList(head) {
let prev = null, cur = head;
while (cur !== null) {
const nxt = cur.next;
cur.next = prev;
prev = cur;
cur = nxt;
}
return prev;
}
Java
static ListNode reverseList(ListNode head) {
ListNode prev = null, cur = head;
while (cur != null) {
ListNode nxt = cur.next;
cur.next = prev;
prev = cur;
cur = nxt;
}
return prev;
}
Cost at a glance
| Access | O(n) |
|---|---|
| Search | O(n) |
| Insert | reverse O(n), merge O(n + m) |
| Delete | middle / cycle check O(n) |
| Space | O(1) extra |
Practice problems (6)
Reverse a list Warm-up
Given the head of a singly linked list, reverse it in place and return the new head. Do not create new nodes; turn the arrows around.
Middle node Warm-up
Given the head of a non-empty singly linked list, return its middle node. With an even number of nodes there are two middles; return the second one.
The answer is shown as the list that starts at the returned node.
Merge two sorted lists Standard
Given the heads of two sorted singly linked lists l1 and l2, merge them into one sorted list by relinking their nodes, and return its head.
Palindrome list Standard
Given the head of a singly linked list, return true if its values read the same forward and backward. Aim for O(n) time and O(1) extra space.
Trace a list reversal Standard
Follow the reversal of 1 → 2 → 3 → 4 with prev, cur and nxt. Answer each question before the step plays.
Find the cycle start Challenge
A singly linked list may end in a loop: the tail points back to an earlier node instead of null. Return the index of the node where the loop begins, or -1 if there is no loop. Use O(1) extra space.
Tests describe the list as values plus pos, the index the tail links back to (-1 for none). The starter's linkTail(head, pos) builds that loop; call it first and do not use pos otherwise.
Next on the path: Stacks: push, pop, peek; array and linked implementations