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 will use the two-pointer technique to solve this problem efficiently:
slow
and fast
, both pointing at the head of the linked list.slow
pointer one step at a time.fast
pointer two steps at a time.fast
pointer reaches the end of the list, the slow
pointer will be at the middle of the list.By using this approach, we are able to find the middle node in a single traversal of the linked list.
#include <iostream>
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* middleNode(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head;
// Move fast pointer two steps and slow pointer one step each time
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};
The time complexity for this solution is (O(n)), where (n) is the number of nodes in the linked list. This is because we are traversing the list only once.
The space complexity is (O(1)) since we are using a constant amount of extra space for the two pointers.
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?