
Sponsored
Sponsored
This technique uses two pointers, 'slow' and 'fast'. Both start at the head of the list. The 'slow' pointer progresses one node at a time while the 'fast' pointer moves two nodes at a time. When the 'fast' pointer reaches the end of the list, the 'slow' pointer will be at the middle node. This works because the 'fast' pointer traverses the list twice as fast as the 'slow' pointer, thus splitting the path lengthwise in half.
Time Complexity: O(n), where n is the number of nodes in the list, because we are iterating through the list once.
Space Complexity: O(1), since we are using a constant amount of space.
1public class ListNode {
2 public int val;
3 public ListNode next;
4 public ListNode(int val = 0, ListNode next = null) {
5 this.val = val;
6 this.next = next;
7 }
8}
9
10public class Solution {
11 public ListNode MiddleNode(ListNode head) {
12 ListNode slow = head;
13 ListNode fast = head;
14 while (fast != null && fast.next != null) {
15 slow = slow.next;
16 fast = fast.next.next;
17 }
18 return slow;
19 }
20}C# models the problem using a ListNode class and a Solution class housing the MiddleNode method, which applies the two-pointer strategy to identify and return the middle node of the list.
This approach involves two passes over the list. The first pass calculates the total number of nodes. In the second pass, we traverse halfway through the list to reach the middle node by stopping at n/2, where n is the number of nodes. This explicitly determines the node that marks the middle of the list.
Time Complexity: O(n) for two full passes through the list.
Space Complexity: O(1) as only a few extra variables are used.
1
Java's solution involves traversing the linked list twice. The first pass calculates the length, and the second pass ends at the middle node, which is then returned.