Problem
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.
Example 1:
graph LR 1 --> 2 --> 3:::RedNode --> 4 --> 5 classDef RedNode fill:#ff0000;
|
|
Example 2:
graph LR 1 --> 2 --> 3 --> 4:::RedNode --> 5 --> 6 classDef RedNode fill:#ff0000;
|
|
Follow up
Follow up - How will you get it in first pass.
Solution
Method 1 - Get the Length and Travel to Middle
Traverse the whole linked list and count the no. of nodes. Now traverse the list again till count/2
and return the node at count/2
.
Code
|
|
Complexity
- ⏰ Time complexity:
O(n)
, where n is length of linked list. - 🧺 Space complexity:
O(1)
Method 2 - Uses One Slow Pointer and One Fast Pointer 🏆
Traverse linked list using two pointers. Move one pointer by one and other pointer by two. When the fast pointer reaches end slow pointer will reach middle of the linked list. This is done in single pass.
Code
|
|
Method 3 - Using a Counter
Initialize mid element as head and initialize a counter as 0. Traverse the list from head, while traversing increment the counter and change mid to mid->next whenever the counter is odd. So the mid will move only half of the total length of the list.
Code
|
|