STOP 09 · LISTS & TREES
Linked Lists and Pointers
Reverse in place, fast and slow pointers O(n) time · O(1) space
- Learn first
- Leads to
Warm up with this one
LC 203Remove Linked List ElementsStuck? Peek at the approach
Use a dummy node to unify head and interior deletions while maintaining the predecessor pointer.
Key points
- Save next before rewiring. Reversal is three moves: save next, point back, step forward.
- When the head may be removed or replaced, start from a dummy node that points at head and return dummy.next.
- A fast pointer taking two steps per slow step finds the middle and detects a cycle; for the k-th node from the end, move a lead pointer k steps first, then advance both at the same speed.
Common pitfalls
- Rewiring head.next before saving it loses the rest of the list.
- Check that fast and fast.next are non-null before touching fast.next.next.
- After splitting a list, forgetting to null out the first half's tail creates a cycle when you merge or traverse.
Watch it run
Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.
Linked list · insert, delete and reverse by rewiring
List 1 → 2 → 3 → 4: insert 9 at position 2, delete position 0, then reverse
Try your own input
- From head
- 1 → 2 → 3 → 4
Each node holds a value and a pointer to the next node. From head you can only walk forward one node at a time.
InvariantBefore changing a pointer, save the node it pointed to, and the list never breaks.
Template
Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 203, with it.
Python
class ListNode:
def __init__(self, val=0, next=None):
self.val, self.next = val, next
def reverse(head):
prev = None
while head:
nxt = head.next # save it before rewiring
head.next = prev
prev, head = head, nxt
return prev
def middle(head):
"""Middle node; the second of the two middles for even lengths."""
slow = fast = head
while fast and fast.next:
slow, fast = slow.next, fast.next.next
return slowC++
struct ListNode {
int val;
ListNode* next;
ListNode(int v, ListNode* n = nullptr) : val(v), next(n) {}
};
ListNode* reverseList(ListNode* head) {
ListNode* prev = nullptr;
while (head) {
ListNode* nxt = head->next; // save it before rewiring
head->next = prev;
prev = head;
head = nxt;
}
return prev;
}
// Middle node; the second of the two middles for even lengths.
ListNode* middle(ListNode* head) {
ListNode *slow = head, *fast = head;
while (fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}Java
class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
ListNode reverse(ListNode head) {
ListNode prev = null;
while (head != null) {
ListNode nxt = head.next; // save it before rewiring
head.next = prev;
prev = head;
head = nxt;
}
return prev;
}
// Middle node; the second of the two middles for even lengths.
ListNode middle(ListNode head) {
ListNode slow = head, fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}Go
type ListNode struct {
Val int
Next *ListNode
}
func reverse(head *ListNode) *ListNode {
var prev *ListNode
for head != nil {
next := head.Next // save it before rewiring
head.Next = prev
prev, head = head, next
}
return prev
}
// middle returns the middle node; the second of the two middles for even lengths.
func middle(head *ListNode) *ListNode {
slow, fast := head, head
for fast != nil && fast.Next != nil {
slow, fast = slow.Next, fast.Next.Next
}
return slow
}Common variants
Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.
Dummy head and a tail pointer to splice a new listO(m + n) time · O(1) space
When a new list is spliced together on the way (merging, partitioning, adding numbers, deleting): start from a dummy node and only ever append at a tail pointer, so the head needs no special case, then return dummy.next. LC 21 (Merge Two Sorted Lists), LC 2 (Add Two Numbers) and LC 86 (Partition List) have this shape.
Python
class ListNode:
def __init__(self, val=0, next=None):
self.val, self.next = val, next
def merge_two(a, b):
"""One sorted list from two, reusing their nodes."""
dummy = tail = ListNode() # a placeholder head: the first node needs no special case
while a and b:
if a.val <= b.val:
tail.next, a = a, a.next
else:
tail.next, b = b, b.next
tail = tail.next
tail.next = a or b # whatever is left is sorted already
return dummy.nextC++
struct ListNode {
int val;
ListNode* next;
ListNode(int v, ListNode* n = nullptr) : val(v), next(n) {}
};
// One sorted list from two, reusing their nodes.
ListNode* mergeTwo(ListNode* a, ListNode* b) {
ListNode dummy(0); // a placeholder head: the first node needs no special case
ListNode* tail = &dummy;
while (a && b) {
ListNode*& smaller = a->val <= b->val ? a : b;
tail->next = smaller;
smaller = smaller->next;
tail = tail->next;
}
tail->next = a ? a : b; // whatever is left is sorted already
return dummy.next;
}Java
class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
// One sorted list from two, reusing their nodes.
ListNode mergeTwo(ListNode a, ListNode b) {
ListNode dummy = new ListNode(0, null), tail = dummy; // the first node needs no special case
while (a != null && b != null) {
if (a.val <= b.val) {
tail.next = a;
a = a.next;
} else {
tail.next = b;
b = b.next;
}
tail = tail.next;
}
tail.next = a != null ? a : b; // whatever is left is sorted already
return dummy.next;
}
}Go
type ListNode struct {
Val int
Next *ListNode
}
// mergeTwo returns one sorted list from two, reusing their nodes.
func mergeTwo(a, b *ListNode) *ListNode {
dummy := &ListNode{} // a placeholder head: the first node needs no special case
tail := dummy
for a != nil && b != nil {
if a.Val <= b.Val {
tail.Next, a = a, a.Next
} else {
tail.Next, b = b, b.Next
}
tail = tail.Next
}
if a != nil { // whatever is left is sorted already
tail.Next = a
} else {
tail.Next = b
}
return dummy.Next
}Reverse in groups of kO(n) time · O(1) space
To reverse one segment or the list group by group: prev waits before the group, count k nodes first (fewer stay as they are), reverse the group in place, reconnect both ends, and move prev to the group's new tail. LC 25 (Reverse Nodes in k-Group), LC 24 (Swap Nodes in Pairs, k = 2) and LC 92 (Reverse Linked List II) share this skeleton.
Python
class ListNode:
def __init__(self, val=0, next=None):
self.val, self.next = val, next
def reverse_k_group(head, k: int):
"""Reverses every full group of k nodes; a shorter tail stays as it is (LC 25)."""
dummy = ListNode(0, head)
prev = dummy # the node before the group being reversed
while True:
tail = prev
for _ in range(k): # is there a full group after prev?
tail = tail.next
if not tail:
return dummy.next
nxt, cur, p = tail.next, prev.next, tail.next
while cur is not nxt: # reverse prev.next..tail, hanging it onto nxt
cur.next, p, cur = p, cur, cur.next
first = prev.next # the group's old first node is now its last
prev.next = tail
prev = firstC++
struct ListNode {
int val;
ListNode* next;
ListNode(int v, ListNode* n = nullptr) : val(v), next(n) {}
};
// Reverses every full group of k nodes; a shorter tail stays as it is (LC 25).
ListNode* reverseKGroup(ListNode* head, int k) {
ListNode dummy(0, head);
ListNode* prev = &dummy; // the node before the group being reversed
while (true) {
ListNode* tail = prev;
for (int i = 0; i < k; i++) { // is there a full group after prev?
tail = tail->next;
if (!tail) return dummy.next;
}
ListNode *nxt = tail->next, *cur = prev->next, *p = nxt;
while (cur != nxt) { // reverse prev->next..tail, hanging it onto nxt
ListNode* after = cur->next;
cur->next = p;
p = cur;
cur = after;
}
ListNode* first = prev->next; // the group's old first node is now its last
prev->next = tail;
prev = first;
}
}Java
class ListNode {
int val;
ListNode next;
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
class Solution {
// Reverses every full group of k nodes; a shorter tail stays as it is (LC 25).
ListNode reverseKGroup(ListNode head, int k) {
ListNode dummy = new ListNode(0, head);
ListNode prev = dummy; // the node before the group being reversed
while (true) {
ListNode tail = prev;
for (int i = 0; i < k; i++) { // is there a full group after prev?
tail = tail.next;
if (tail == null) return dummy.next;
}
ListNode nxt = tail.next, cur = prev.next, p = nxt;
while (cur != nxt) { // reverse prev.next..tail, hanging it onto nxt
ListNode after = cur.next;
cur.next = p;
p = cur;
cur = after;
}
ListNode first = prev.next; // the group's old first node is now its last
prev.next = tail;
prev = first;
}
}
}Go
type ListNode struct {
Val int
Next *ListNode
}
// reverseKGroup reverses every full group of k nodes; a shorter tail stays as it is (LC 25).
func reverseKGroup(head *ListNode, k int) *ListNode {
dummy := &ListNode{0, head}
prev := dummy // the node before the group being reversed
for {
tail := prev
for i := 0; i < k; i++ { // is there a full group after prev?
tail = tail.Next
if tail == nil {
return dummy.Next
}
}
next, cur, p := tail.Next, prev.Next, tail.Next
for cur != next { // reverse prev.Next..tail, hanging it onto next
cur.Next, p, cur = p, cur, cur.Next
}
first := prev.Next // the group's old first node is now its last
prev.Next = tail
prev = first
}
}Why it works
- Reversal invariant: prev heads the reversed part and cur heads the untouched part, and the two are disconnected. Each step saves cur.next, points cur at prev and moves both forward, keeping the invariant; when cur is null, prev is the new head.
- Fast and slow pointers on a cycle: once both are inside it, the fast pointer gains one node per step, so the gap shrinks by one each step (mod the cycle length) and they meet within one lap; with no cycle the fast pointer reaches null first.
- A dummy node makes deleting the head the same operation as deleting any other node: every real node has a predecessor, so there is no special case.
Say it in 30 seconds
When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.
链表题我先想清楚指针改动的顺序。反转时维护 prev 和 cur:先存下 cur.next,再把 cur 指回 prev,然后两个指针一起前进,cur 为空时 prev 就是新头。可能删头或换头时加一个哑节点,所有真实节点都有前驱,省掉特判。判环或找中点用快慢指针,进环后快指针每步追近一格,一定会相遇。都是 O(n) 时间、O(1) 空间。For linked lists I first fix the order of pointer changes. To reverse, I keep prev and cur: save cur.next, point cur back at prev, then advance both, and when cur is null prev is the new head. When the head might change I add a dummy node so every real node has a predecessor. For cycles and midpoints I use fast and slow pointers, and inside a cycle the fast one closes the gap by one node per step, so they must meet.Grade yourself
Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.
Quick quiz
4 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice
Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.
Template drills
Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.
These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.
class ListNode:
def __init__(self, val=0, next=None):
self.val, self.next = val, next
return slowPractice by stage
This stop's 27 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.
Foundation 6
| # | Problem | Approach | Rating |
|---|---|---|---|
| 203 | Remove Linked List Elements | Use a dummy node to unify head and interior deletions while maintaining the predecessor pointer. | |
| 206 | Reverse Linked List | Reverse a linked list iteratively, saving the successor before changing each pointer. | |
| 21 | Merge Two Sorted Lists | Merge two sorted linked lists, handling empty inputs and remaining tails. | |
| 876 | Middle of the Linked List | Locate the midpoint with slow and fast pointers, distinguishing stopping conditions for odd and even lengths. | |
| 83 | Remove Duplicates from Sorted List | Exploit sorted order to deduplicate in place while preserving links between retained nodes. | |
| 141 | Linked List Cycle | Detect a cycle with slow and fast pointers, using a meeting rather than reaching the end as the termination condition. |
Core 16
| # | Problem | Approach | Rating |
|---|---|---|---|
| 160 | Intersection of Two Linked Lists | Switch the two pointers to the opposite heads to cancel length differences and detect intersection by node identity. | |
| 19 | Remove Nth Node From End of List | Delete the nth node from the end using pointers a fixed distance apart, including deletion of the head. | |
| 82 | Remove Duplicates from Sorted List II | Remove all nodes with repeated values rather than retaining one, keeping the predecessor of each duplicate run. | |
| 328 | Odd Even Linked List | Split nodes by odd and even positions, then reconnect the chains without creating a tail cycle. | |
| 86 | Partition List | Partition a linked list stably, preserving internal order on both sides and disconnecting obsolete links. | |
| 24 | Swap Nodes in Pairs | Swap adjacent pairs locally, reconnecting the predecessor, current pair, and successor completely. | |
| 92 | Reverse Linked List II | Reverse only the requested interval and reconnect it to both surrounding portions. | |
| 61 | Rotate List | Turn rotation into forming a cycle and breaking it, handling k larger than the list length. | |
| 142 | Linked List Cycle II | Derive the cycle entry from the slow-fast meeting point using distances around the cycle. | |
| 234 | Palindrome Linked List | Find the midpoint and reverse the second half to test a palindrome, considering restoration of the original structure. | |
| 143 | Reorder List | Combine midpoint detection, reversal, and alternating merge without losing unprocessed nodes. | |
| 2 | Add Two Numbers | Simulate addition digit by digit, uniformly handling different lengths and a final carry. | |
| 445 | Add Two Numbers II | Use stacks to add lists with the most significant digit first without requiring changes to the original lists. | |
| 138 | Copy List with Random Pointer | Copy a random-pointer list using node mappings and an understanding of original-object identity. | |
| 147 | Insertion Sort List | Implement insertion sort on a linked list, maintaining the sorted region and locating insertion positions. | |
| 708 | Insert into a Sorted Circular Linked List 🔒 | Find an insertion point in a sorted circular list, handling the maximum-to-minimum break and all-equal nodes. |
Advanced 5
| # | Problem | Approach | Rating |
|---|---|---|---|
| 430 | Flatten a Multilevel Doubly Linked List | Flatten a multilevel doubly linked list while maintaining next, prev, child, and reconnection positions. | |
| 148 | Sort List | Apply merge sort to a linked list, practicing splitting and merging while explaining O(n log n) complexity. | |
| 23 | Merge k Sorted Lists | Merge multiple sorted lists with a min-heap or divide and conquer, analyzing the effects of node count and list count. | |
| 25 | Reverse Nodes in k-Group | Reverse groups of k nodes while leaving a shorter final group unchanged and maintaining group boundaries. | |
| 1171 | Remove Zero Sum Consecutive Nodes from Linked List | Use repeated prefix sums to locate and remove consecutive linked-list nodes whose sum is zero. |
OA questions on this topic 4
- Remove Even-Value Nodes from Linked ListIBM
- Binary Linked List to DecimalCisco
- Delete Nodes Greater Than XCisco
- Implement an LRU CacheGeico
Core Skills
Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.