You are given the head
of a singly linked list. Your task is to write a function that returns the middle node of this linked list. If the linked list has an even number of nodes, return the second middle node.
For example:
1 -> 2 -> 3 -> 4 -> 5
, the function should return the node with value 3
.1 -> 2 -> 3 -> 4 -> 5 -> 6
, the function should return the node with value 4
.Consider the following constraints:
[1, 100]
.1 <= Node.val <= 100
Describe your approach, analyze its time and space complexity, and handle potential edge cases. Provide the code implementation in Java.
Given the head
of a singly linked list, return the middle node of the linked list.
If there are two middle nodes, return the second middle node.
A straightforward approach involves iterating through the linked list twice. The first pass determines the length of the list. The second pass advances to the middle node.
count
).middle = count / 2
. If count
is even, this gives the index of the second middle node.middle
times to reach the middle node.class Solution {
public ListNode middleNode(ListNode head) {
int count = 0;
ListNode current = head;
while (current != null) {
count++;
current = current.next;
}
int middle = count / 2;
current = head;
for (int i = 0; i < middle; i++) {
current = current.next;
}
return current;
}
}
This approach uses two pointers, often called "slow" and "fast" pointers. The slow pointer moves one step at a time, while the fast pointer moves two steps at a time. When the fast pointer reaches the end of the list, the slow pointer will be at the middle node.
slow
and fast
, both pointing to the head of the linked list.fast
pointer and fast.next
are not null, advance slow
by one step and fast
by two steps.fast
reaches the end), slow
will be pointing to the middle node.slow
pointer.class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
}
return slow;
}
}
fast.next
will be null. The slow
pointer will be returned, which is the head.