Problems on linked nodes
After this: Reverse a linked list with three pointers and merge two sorted lists with a placeholder node.
On this page · 4 sections · 3 checks
The rows in the last two lessons let you jump to any position. A linked list does not: you start at the head and follow one next pointer at a time, as in Walking a list in the linked-lists tutorial. Interviewers like linked-list problems because a single line in the wrong order loses the rest of the list. This lesson works two of them.
Both use the class from the linked-lists tutorial: a Node with a value and a next. This version adds one method, __repr__toString, that prints a node and everything after it, such as 1 -> 4 -> 6 -> None1 -> 4 -> 6 -> null. The trace band shows each box that way.
6. Reverse a linked list
Pattern: three pointers walking once. prev is the part already turned round, cur is the node being turned, and nxt keeps the rest of the list safe. Each step points cur backwards, at prev, and then moves all three one node on.
def reverse(head): prev = None cur = head while cur: nxt = cur.next cur.next = prev prev = cur cur = nxt return prevstatic Node reverse(Node head) { Node prev = null; Node cur = head; while (cur != null) { Node nxt = cur.next; cur.next = prev; prev = cur; cur = nxt; } return prev;}The order inside the loop matters. nxt = cur.next must come first: the next line, the flip, overwrites cur.next, and without nxt the rest of the list would be lost. When cur falls off the end, prev is on the old last node, which is the new head.
Pinned example. 1 → 2 → 3 → 4 gives 4 → 3 → 2 → 1. An empty list gives an empty list, because the loop never runs and prev is still Nonenull. One node gives the same node back.
Cost. O(n) time: each node is flipped once. Extra memory: O(1), three pointers, because the existing nodes are reused.
- ReverseReverse the list one step at a time. After each flip, read where prev, cur and next sit.
Run an operation to begin.
7. Merge two sorted lists
Pattern: two pointers, one per list, and a placeholder first node. The smallest node not yet used is always at the front of one of the two lists. So compare the two fronts, link the smaller one onto the end of the answer, and move that list on by one.
The answer needs somewhere to start before its first real node is chosen. A is a placeholder for that. tail starts on it and always points at the last node of the answer so far. At the end, the answer is dummy.next.
- Run the programRun it and step through. Watch a and b inside merge: each time, the smaller front node is linked after tail, and that list moves on by one.
class Node: def __init__(self, value, next=None): self.value = value self.next = next
def __repr__(self): return f"{self.value} -> {self.next}"
def merge(a, b): dummy = Node(0) tail = dummy while a and b: if a.value <= b.value: tail.next = a a = a.next else: tail.next = b b = b.next tail = tail.next tail.next = a if a else b return dummy.next
head = merge(Node(1, Node(4, Node(6))), Node(2, Node(3, Node(7, Node(8)))))run the program to see its boxes
nothing printed yetPress Run it, then step through the program one line at a time.
- lines
- 0
- prints
- 0
- calls
- 0
Follow 1 → 4 → 6 and 2 → 3 → 7 → 8:
- 1 is smaller than 2. Link 1 after the dummy;
amoves on to 4. - 2 is smaller than 4. Link 2;
bmoves on to 3. Then 3 is smaller than 4: link 3;bmoves on to 7. - 4 is smaller than 7: link 4. Then 6 is smaller than 7: link 6.
ais now empty. - The loop stops. The last line links the rest of
b, 7 → 8, in one step.
The answer is 1 → 2 → 3 → 4 → 6 → 7 → 8. Merging an empty list with 1 → 2 gives 1 → 2, and 1 → 3 with 1 → 2 gives 1 → 1 → 2 → 3. When the two fronts are equal, <= takes the node from the first list.
Cost. O(n + m) time, where n and m are the lengths of the two lists: each node is linked once. Extra memory: O(1), one dummy node and two pointers, because the existing nodes are relinked, not copied.
Run it
Check yourself
Two linked lists are each sorted from smallest to largest. You must join them into one sorted list, using the nodes you already have. Which pattern fits?
Reversing 1 → 2 → 3 → 4. After two flips, what does the list that starts at prev look like? cur is now on 3.
merge starts by making a placeholder node, dummy, that holds 0 and is never part of the answer. Why?
- Reverse a linked list with prev, cur and nxt, saving the rest of the list before each flip.
- Merge two sorted lists by comparing their two front nodes and linking the smaller one each time.
- Explain what the dummy node is for: the first real node needs no special case, and the answer is the node after it.
- Say that both solutions are O(n) or O(n + m) time with O(1) extra memory, because they relink the nodes they are given.