Practice: linked lists
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Six core linked-list patterns—dummy heads, 3-pointer reversal, fast/slow pointers, gap pointers, sorted merges, and sentinel lists—work together. Combining these building blocks solves almost every linked-list interview problem in O(1) extra space.
Linked-list pattern selector
Before writing code on any linked-list problem, match the problem's goal to one of the six core patterns:
- Head might change (insert, delete, partition, filter): allocate
Node dummy = new Node(0, head)and returndummy.next. - Middle, cycle, or palindrome: use Fast and Slow Pointers (
slowmoves 1 step,fastmoves 2). - k-th from the end or rotate by k: use Two Pointers at Distance k, or link
tail.next = head.
For backward traversal in O(1) space, reverse in place (prev, curr, nextTemp). For O(1) removal or promotion by key, pair a HashMap<Key, DNode> with a Sentinel Doubly Linked List. For O(n log n) sorting, split at the first middle (fast = head.next), sort both halves, and merge.
- Always test your code mentally on
null,[1], and[1, 2]before submitting. - When splitting a list into two parts, sever
.nextat the cut point (slow.next = null) to avoid cycles.
Problems 1–3: Swap Nodes in Pairs, Partition List, and Remove Duplicates II
Three problems practise the dummy head: Swap Nodes in Pairs, Partition List and Remove Duplicates II.
- In Partition List, set
greaterTail.next = null;at the end sogreaterTailcannot form a cycle. - In Remove Duplicates II, only advance
prevwhencurris confirmed to be unique (curr.next == null || curr.val != curr.next.val).
Example 1 · Problems 1 & 2: Swap Nodes in Pairs and Stable Partition List
public class SwapAndPartitionDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node swapPairs(Node head) { Node dummy = new Node(0, head); Node prev = dummy; while (prev.next != null && prev.next.next != null) { Node first = prev.next; Node second = prev.next.next; first.next = second.next; second.next = first; prev.next = second; prev = first; } return dummy.next; }
public static Node partition(Node head, int x) { Node lessDummy = new Node(0, null), lessTail = lessDummy; Node greaterDummy = new Node(0, null), greaterTail = greaterDummy; for (Node curr = head; curr != null; curr = curr.next) { if (curr.val < x) { lessTail.next = curr; lessTail = curr; } else { greaterTail.next = curr; greaterTail = curr; } } greaterTail.next = null; // critical: sever old link to avoid cycle! lessTail.next = greaterDummy.next; return lessDummy.next; }
static String format(Node h) { StringBuilder sb = new StringBuilder(); for (Node c = h; c != null; c = c.next) sb.append(c.val).append(" -> "); return sb.append("null").toString(); }
public static void main(String[] args) { Node a = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, null))))); System.out.println("Swapped pairs: " + format(swapPairs(a)));
Node b = new Node(1, new Node(4, new Node(3, new Node(2, new Node(5, new Node(2, null)))))); System.out.println("Partition < 3: " + format(partition(b, 3))); }}Swapped pairs: 2 -> 1 -> 4 -> 3 -> 5 -> null Partition < 3: 1 -> 2 -> 2 -> 4 -> 3 -> 5 -> null
What this code does
- In
swapPairs,first(1) moves to the second spot (2 -> 1), soprev = firstprepares the next pair. - In
partition, two dummy heads (lessDummyandgreaterDummy) partition the list in one O(n) pass.
- Swap Nodes in Pairs: swap every two adjacent nodes in place (
1 -> 2 -> 3 -> 4becomes2 -> 1 -> 4 -> 3). Use a dummy head and rewireprev -> first -> second -> nextPairintoprev -> second -> first -> nextPair, then setprev = first. - Partition List: place all nodes
< xbefore all nodes>= xin O(1) space. Use two dummy heads (lessDummyandgreaterDummy), append each node, setgreaterTail.next = null, and linklessTail.next = greaterDummy.next. - Remove Duplicates II: delete all duplicate numbers (
1 -> 2 -> 3 -> 3 -> 4 -> 4 -> 5becomes1 -> 2 -> 5). Whencurr.next != null && curr.val == curr.next.val, skip the entire duplicate run and setprev.next = curr.
Problems 4–5: Sort List (Bottom-Up/Top-Down Merge Sort) and Remove Zero Sum Sublists
In Sort List, sort an unsorted linked list in O(n log n) time using Merge Sort. Find the first middle (slow = head, fast = head.next), cut Node mid = slow.next; slow.next = null;, sort head and mid, and merge.
Example 2 · Problems 3 & 4: Remove All Duplicate Numbers II and Merge Sort on a Linked List
public class DedupeAndSortListDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node deleteDuplicatesII(Node head) { Node dummy = new Node(0, head), prev = dummy, curr = head; while (curr != null) { if (curr.next != null && curr.val == curr.next.val) { int dupVal = curr.val; while (curr != null && curr.val == dupVal) { curr = curr.next; } prev.next = curr; // skip entire duplicate block } else { prev = curr; curr = curr.next; } } return dummy.next; }
public static Node sortList(Node head) { if (head == null || head.next == null) return head; Node slow = head, fast = head.next; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; } Node mid = slow.next; slow.next = null; return merge(sortList(head), sortList(mid)); }
private static Node merge(Node l1, Node l2) { Node dummy = new Node(0, null), tail = dummy; while (l1 != null && l2 != null) { if (l1.val <= l2.val) { tail.next = l1; l1 = l1.next; } else { tail.next = l2; l2 = l2.next; } tail = tail.next; } tail.next = (l1 != null) ? l1 : l2; return dummy.next; }
static String format(Node h) { StringBuilder sb = new StringBuilder(); for (Node c = h; c != null; c = c.next) sb.append(c.val).append(" -> "); return sb.append("null").toString(); }
public static void main(String[] args) { Node dup = new Node(1, new Node(1, new Node(2, new Node(3, new Node(3, new Node(4, null)))))); System.out.println("Distinct only: " + format(deleteDuplicatesII(dup)));
Node unsorted = new Node(4, new Node(2, new Node(1, new Node(3, null)))); System.out.println("Sorted list: " + format(sortList(unsorted))); }}Distinct only: 2 -> 4 -> null Sorted list: 1 -> 2 -> 3 -> 4 -> null
What this code does
- On
1 -> 1 -> 2 -> 3 -> 3 -> 4,deleteDuplicatesIIremoves both1s and both3s, leaving2 -> 4. - In
sortList,fast = head.nextis essential: on4 -> 2,fast = headleavesslowon2and recurses forever.
Example 3 · Problem 5: Remove Zero Sum Consecutive Sublists (Prefix Sum + Dummy Node)
import java.util.HashMap;import java.util.Map;
public class RemoveZeroSumSublistsDemo { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node removeZeroSumSublists(Node head) { Node dummy = new Node(0, head); Map<Integer, Node> lastSeen = new HashMap<>(); int prefix = 0; for (Node curr = dummy; curr != null; curr = curr.next) { prefix += curr.val; lastSeen.put(prefix, curr); } prefix = 0; for (Node curr = dummy; curr != null; curr = curr.next) { prefix += curr.val; curr.next = lastSeen.get(prefix).next; } return dummy.next; }
static String format(Node h) { StringBuilder sb = new StringBuilder(); for (Node c = h; c != null; c = c.next) sb.append(c.val).append(" -> "); return sb.append("null").toString(); }
public static void main(String[] args) { Node a = new Node(1, new Node(2, new Node(-3, new Node(3, new Node(1, null))))); System.out.println("After removing zero-sum: " + format(removeZeroSumSublists(a))); }}After removing zero-sum: 3 -> 1 -> null
What this code does
- At
dummy,prefix = 0. After1, 2, -3,prefixis0again at node-3, solastSeen.get(0)is node-3. - In Pass 2, when
curris atdummy(prefix = 0),curr.next = lastSeen.get(0).nextjumps directly over1 -> 2 -> -3to3.
In Remove Zero Sum Consecutive Nodes, delete consecutive ranges that sum to 0 (1 -> 2 -> -3 -> 3 -> 1 becomes 3 -> 1). Use Prefix Sum + HashMap with a dummy node! If two nodes u and v share the same prefix sum, the nodes u.next .. v sum to 0. In Pass 1, walk from dummy and record the last node seen for each prefix sum (lastSeen.put(prefix, curr)). In Pass 2, walk from dummy again and set curr.next = lastSeen.get(prefix).next to jump over every zero-sum range.
Module quiz
Questions from the whole module. Your first answer is your score.
Problems
Graded easy to hard, using everything from this module.
Try each one yourself first. Use the hint if you get stuck. Mark it as done when it works.
Exercise 1· Easy
Given int[] nums and Node head, delete every node whose value is in nums. Use a HashSet<Integer> and a dummy node, and test removing {1, 2, 3} from 1 -> 2 -> 3 -> 4 -> 5.
import java.util.HashSet;import java.util.Set;
public class DeleteNodesInSetSolution { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node modifiedList(int[] nums, Node head) { // Put nums in a HashSet and filter the list using a dummy head return head; }
public static void main(String[] args) { Node h = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, null))))); h = modifiedList(new int[]{1, 2, 3}, h); StringBuilder sb = new StringBuilder(); for (Node c = h; c != null; c = c.next) sb.append(c.val).append(" "); System.out.println(sb.toString().trim()); }}4 5
Exercise 2· Easy
Between every adjacent pair (curr, curr.next), insert a node with gcd(curr.val, curr.next.val). Test on 18 -> 6 -> 10 -> 3.
public class InsertGCDListSolution { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node insertGreatestCommonDivisors(Node head) { // Insert gcd(curr.val, curr.next.val) between every adjacent pair return head; }
public static void main(String[] args) { Node h = new Node(18, new Node(6, new Node(10, new Node(3, null)))); insertGreatestCommonDivisors(h); StringBuilder sb = new StringBuilder(); for (Node c = h; c != null; c = c.next) sb.append(c.val).append(" "); System.out.println(sb.toString().trim()); }}18 6 6 2 10 1 3
Exercise 3· Medium
Write insertionSortList(Node head) to sort a list using Insertion Sort. Keep a sorted prefix at dummy, find prev (prev.next.val < curr.val), and splice curr after prev. Test on 4 -> 2 -> 1 -> 3.
public class InsertionSortListSolution { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node insertionSortList(Node head) { // Insert each node from head into a sorted list starting at dummy return head; }
public static void main(String[] args) { Node h = new Node(4, new Node(2, new Node(1, new Node(3, null)))); h = insertionSortList(h); StringBuilder sb = new StringBuilder(); for (Node c = h; c != null; c = c.next) sb.append(c.val).append(" "); System.out.println(sb.toString().trim()); }}1 2 3 4
Exercise 4· Medium
Given head and 1-based k, swap the values of the k-th node from start and end. Test on 1 -> 2 -> 3 -> 4 -> 5 with k = 2.
public class SwapKthNodesSolution { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node swapNodes(Node head, int k) { // Find k-th from start and k-th from end in one pass and swap their val fields return head; }
public static void main(String[] args) { Node h = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, null))))); swapNodes(h, 2); StringBuilder sb = new StringBuilder(); for (Node c = h; c != null; c = c.next) sb.append(c.val).append(" "); System.out.println(sb.toString().trim()); }}1 4 3 2 5
Exercise 5· Hard
Write sortListBottomUp(Node head) to sort a list in O(n log n) time and O(1) space (no recursion). Merge adjacent blocks of size step = 1, 2, 4, 8, ... and test on 7 -> 3 -> 9 -> 1 -> 5 -> 2 -> 8 -> 4 -> 6.
public class BottomUpMergeSortList { static class Node { int val; Node next; Node(int val, Node next) { this.val = val; this.next = next; } }
public static Node sortListBottomUp(Node head) { // Iterative bottom-up merge sort with step = 1, 2, 4, 8... return head; }
public static void main(String[] args) { int[] vals = {7, 3, 9, 1, 5, 2, 8, 4, 6}; Node head = null; for (int i = vals.length - 1; i >= 0; i--) head = new Node(vals[i], head); head = sortListBottomUp(head); StringBuilder sb = new StringBuilder(); for (Node c = head; c != null; c = c.next) sb.append(c.val).append(" "); System.out.println(sb.toString().trim()); }}1 2 3 4 5 6 7 8 9
Exercise 6· Hard
Reorder a singly linked list so nodes alternate from front and back. Given 1 -> 2 -> 3 -> 4 -> 5, transform it to 1 -> 5 -> 2 -> 4 -> 3 in place.
public class ReorderListPracticeSolution { static class Node { int val; Node next; Node(int val) { this.val = val; } Node(int val, Node next) { this.val = val; this.next = next; } }
public static void reorderList(Node head) { // TODO: Find middle, reverse second half, and interleave }
public static void main(String[] args) { Node head = new Node(1, new Node(2, new Node(3, new Node(4, new Node(5, null))))); reorderList(head); StringBuilder sb = new StringBuilder(); for (Node c = head; c != null; c = c.next) { sb.append(c.val).append(" "); } System.out.println(sb.toString().trim()); }}1 5 2 4 3
Interview questions
Questions interviewers ask on this topic.
What's next
You finished the preview of Linked Lists
Java Programming has 26 sections, 252 modules and 1949 lessons. An account opens every lesson and saves your progress.
Finish up
Mark complete & continue
Next: Stacks: last in, first out