How to find the middle element of a linked list in one pass?

Solution

You can find the middle element of Linked list in one pass using below-mentioned logic:

For this you have to maintain two pointers lets say first and second. At the time of iteration increment the first pointer each time while increment the second pointer in every second iteration. When the first pointer reaches till end of the list, the second pointer will be pointing to the middle of the linked list.

For example: Given linked list has 5 elements as shown and we have first and second pointer. First pointer increments after each pass whereas second pointer increments after every second pass. When the first pointer reach to end of linked list, second pointer reach to middle of linked list.

Find Middle Element of List

Share this thread

Comments

Comments
comments powered by Disqus

Navigation

Social Media