~/DHRUVUpskilling
← board/DSA/Fast and Slow Pointer/dsa-fast-and-slow-pointer-03
Solved·25 Aug

Middle of the Linked List

DifficultyMedium
PatternFast and Slow Pointer
TrackDSA
tl;dr

Given the head of a singly linked list, return the middle node of the linked list. If the number of nodes in the linked list is even, there will be two middle nodes, so return the second one.

full write-up

Constraints

Let n be the number of nodes in a linked list.

  • 1 ≤ n ≤ 100
  • 1 ≤ node.data ≤ 100
  • head ≠ NULL

We can use slow and fast pointers to find middle of linked list. The fast pointer will be twice the speed of slow pointer so when fast pointer reaches the end. The slow pointer will be in middle

function findMiddle(head){
let slow=head;
let fast= head;


while(fast!==null && fast.next!==null){

slow=slow.next;
fast=fast.next.next;

}

return slow;

}


Complexity

Time: O(n)

Space: O(1)