Find Middle of the Linked List.Using Two Pointer approach.

Table of contents

No heading

No headings in the article.

Approach - Initialize two pointers, slow and fast, to the head of the linked list.

  1. we will Traverse the linked list using the slow and fast pointers. we will Move the slow pointer one node at a time and the fast pointer two nodes at a time. until the fast pointer reaches the end of the Linked list.

  2. When the fast pointer reaches the end of the list, the slow pointer will be pointing to the middle node of the linked list.

  3. we will Return the slow pointer.

class Solution { public: ListNode middleNode(ListNode head) { ListNode slow=head; ListNode fast=head; while(fast && fast->next){ fast=fast->next->next; slow=slow->next;

} return slow; }