Leetcode 876. Middle of the Linked List
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.
We can solve this problem using a two-pointer approach:
slow and fast, both set to the head of the linked list.slow by one step and fast by two steps in each iteration.fast reaches the end of the list (or the node before the end in the case of even length lists), slow will be at the middle node.class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public 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;
}
}
slow and fast pointers are initialized to point to the head of the linked list.while loop checks whether fast and fast.next are not null.slow moves one step each time (slow = slow.next).fast moves two steps each time (fast = fast.next.next).fast or fast.next is null, slow will be at the middle node of the linked list.slow pointer, which now points to the middle node.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?