47
loading...
This website collects cookies to deliver better user experience
LinkedList
Data structure.head
, return a middle node of the linked list.💡 Give yourself at least 15-20 mins to figure out the solution :)
👀 Observation: If you recall from the last post, we can reach the middle node after floor(L/2)
iterations.
fast
and slow
both pointing to head
initially.Move fast
double the speed than slow
untill fast
becomes NULL or it has reached the last node.
//pseudo code
while fast!=NULL and fast->next != NULL
fast = fast->next->next
slow = slow->next
return slow
.
fast
will point to the last node after floor(L/2)
iterations.fast
will become NULL after traversing the entire list in floor(L/2)
iterations.floor(L/2)
iterations, and by that time slow
would be pointing to the required middle node.//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) {}
};
ListNode *middleNode(ListNode *head)
{
ListNode *fast;
ListNode *slow;
fast = slow = head;
//make fast reach the end of the list by moving it double time the slow
while (fast != nullptr && fast->next != nullptr)
{
fast = fast->next->next;
slow = slow->next;
}
//* now slow will point to the required node
return slow;
}
N
: Length of Linked List.47