Middle of the Linked List
Return the middle node of a linked list in a single walk, with one pointer moving twice as fast as the other.
A singly linked list is a chain of nodes: each node holds a value and a link to the next node, and the last node links to nullhead
Example 1
Output: [3, 4, 5]
Explanation: the middle node is 3. Returning it also returns the nodes after it, so the output reads from 3 to the end.
Example 2
Output: [4, 5, 6]
Explanation: 3 and 4 are both middle nodes, and the second one is 4.
The Idea
Finding the middle book on a shelf is easy, because you see all the books at once. A linked list does not give you that view. You hold only the first node, and from each node you can step only to the next one, so you cannot tell how long the list is without walking it.
In Example 1 the list is 1, 2, 3, 4, 5. Node 3 has two nodes on each side, so it is the middle. In Example 2 the list is 1 to 6, and no single node sits in the centre: 3 and 4 share it, and the problem picks 4. So how do we reach the middle when we do not know the length?
Imagine two people walking along the list from the first node. One takes one node per round, the other takes two. When the faster one runs out of list, the slower one has covered half the distance, so it stands on the middle. A variable that refers to a node is called a pointer, and here the two walkers are two pointers, named slowfast
In the row labelled start, both pointers are on node 1. After round 1, slowfastfastnullslow
With the five nodes of Example 1, the walk ends one step sooner. After round 2, fastslow
Solution Approach
Turning that idea into code means looking at the simple way of counting first, then settling when the fast pointer must stop and which middle that stop gives for an even length.
Counting first, then walking
Why not just count the nodes? That works: walk the whole list to count n nodes, then start again from head
When the fast pointer stops
When can fastfast = fast.next.nextfastfast.nextfast != null && fast.next != nullfast != nullfastfast.next != nullfast
The order of the two checks matters. Java checks the right side of &&fast.nextfastnull
Which of the two middles
Why does the walk land on 4 and not on 3? Because fastslowfast.next != null && fast.next.next != nullfastslow
Java Solution
The method middleNode
- First, point two variables,
andslow , atfast .head - Then loop while
. Each round,fast != null && fast.next != null moves one node withslow , andslow = slow.next moves two withfast .fast = fast.next.next - When the loop ends, return
, the middle node. The nodes after it stay linked to it, so printing from it shows the rest of the list.slow
Around the method, a small ListNodebuildshowmain
public class MiddleOfLinkedList {
static class ListNode {
int val;
ListNode next;
ListNode(int val) { this.val = val; }
}
public static ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next; // one step
fast = fast.next.next; // two steps
}
return slow;
}
static ListNode build(int... values) {
ListNode dummy = new ListNode(0);
ListNode tail = dummy;
for (int v : values) {
tail.next = new ListNode(v);
tail = tail.next;
}
return dummy.next;
}
static String show(ListNode node) {
StringBuilder sb = new StringBuilder("[");
for (; node != null; node = node.next) {
sb.append(node.val).append(node.next != null ? ", " : "");
}
return sb.append("]").toString();
}
public static void main(String[] args) {
System.out.println(show(middleNode(build(1, 2, 3, 4, 5))));
System.out.println(show(middleNode(build(1, 2, 3, 4, 5, 6))));
System.out.println(show(middleNode(build(7))));
System.out.println(show(middleNode(build(1, 2))));
}
}
Running it prints:
[3, 4, 5]
[4, 5, 6]
[7]
[2]
The six-node list gives [4, 5, 6][3, 4, 5]
Look at the last two lines. For the list [7]fastnextnull[1, 2]slowfastnull
Complexity
The work is a single walk of the two pointers, which stops when fast
- Time: O(n), for a list of n nodes:
passes over each node at most once, two per round, so the loop runs about n / 2 rounds, each a few pointer moves.fast - Space: O(1). However long the list is, the method keeps only the two pointers. It neither counts the nodes nor copies them into an array.
Finding the middle is also the first step of