
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.
1#include <stdio.h>
2#include <stdlib.h>
3
4struct ListNode {
5 int val;
6 struct ListNode *next;
7};
8
9struct ListNode* middleNode(struct ListNode* head) {
10 struct ListNode* slow = head;
11 struct ListNode* fast = head;
12 while (fast != NULL && fast->next != NULL) {
13 slow = slow->next;
14 fast = fast->next->next;
15 }
16 return slow;
17}In C, we define a simple singly linked list structure and implement the two-pointer approach to find the middle node. The 'slow' pointer advances one step while the 'fast' pointer advances two steps, and once 'fast' reaches the end, 'slow' will be pointing at the middle node.
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
Python computes the linked list's length during a first traversal, and then advances through half the nodes to fetch the middle one for the return statement.