Friday, July 4, 2014

Finding middle of the singly linked list

Pseudo Code :
There can be Bruit force approach applied in which first finding a length of linked list n and in second step move pointer to n/2 node which is the middle of the linked list.But there is also easier and efficient approach which is mentioned below.

Ex :
Linked List : 1 ->2 ->3 ->4 ->5 ->6 ->7
Point p1 to node 1 and p2 with node 3.
p1 :1 -> 2 ->3
p2: 3 -> 5 -> 7

Steps :
1) Have to pointers p1 and p2.
2) Move one pointer p1 with twice the number of nodes w.r.t to pointer p2.
3) By the time p1 approaches the end of the linked list p2 will point to middle node of the linked list.

No comments:

Post a Comment