Finding Median in a Sorted Linked List

• Difficulty Level : Medium
• Last Updated : 08 Jun, 2021

Given A sorted linked list of elements. The task is to find the median in the given Sorted Linked List.
We know that median in a sorted array is the middle element.

Procedure to find median of N sorted numbers:

if N is odd:
median is N/2th element
else
median is N/2th element + (N/2+1)th element

Examples:

Input : 1->2->3->4->5->NULL
Output : 3

Input : 1->2->3->4->5->6->NULL
Output : 3.5

Simple approach

1. Traverse the linked list and count all elements.
2. if count is odd then again traverse the linked list and find n/2th element.
3. if count is even then again traverse the linked list and find:
(n/2th element+ (n/2+1)th element)/2

Note: The above solution traverse the linked list two times.

Efficient Approach: an efficient approach is to traverse the list using two pointers to find the number of elements. See method 2 of this post.
We can use the above algorithm for finding the median of the linked list. Using this algorithm we won’t need to count the number of element:

1. if the fast_ptr is Not NULL then it means linked list contain odd element we simply print the data of the slow_ptr.
2. else if fast_ptr reach to NULL its means linked list contain even element we create backup of the previous node of slow_ptr and print (previous node of slow_ptr+ slow_ptr->data)/2

Below is the implementation of the above approach: