Middle of the Linked List
Link: https://leetcode.com/problems/middle-of-the-linked-list/
Constraints:
The number of nodes in the list is in the range [1, 100].
1 <= Node.val <= 100
Idea
Use two pointers. Slow pointer advance one node at a time, while fast pointer advances two nodes at a time. When the fast pointer reaches the end, slow pointer is pointing to the middle node.
Code
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;
}
}
- Time: O(n).
- Space: O(1).