Finding Median in a Sorted Linked List in C++

C++Server Side ProgrammingProgramming

In this problem, we are given a sorted linked list consisting of N elements. Our task is to finding Median in a Sorted Linked List.

Sorted Linked List is a simple linked list in which all elements are sorted in a specific order. Example − 4 -> 6 -> 7 -> 9 -> NULL

Median is the middle elements of the linked list. It can be found as if N is odd : median is (n/2)th element

if N is even −s median is average of (n/2)th element and (n/2 + 1)th element.

Let's take an example to understand the problem,

Input: 2 -> 3 -> 4 -> 6 -> 9 -> NULL
Output: 4

Solution Approach

A simple solution to the problem is by counting all the elements of the linked list by traversing it.

Now, if the count is odd, we will again traverse the linked list till N/2th element of the linked list.

If the count is even, we will traverse till N/2th element and N/2 + 1 th element, add them and divide by 2.

Alternate approach

Another approach to solve the problem, is by traversing the linked list using a two pointer traversal and find the count of elements of the linked list.

Here's an algorithm to find the median without counting the number of elements. Their are two pointers pointer1 and pointer2, based on the condition, we can have,

If pointer1 is not NULL, pointer2 is median.

If pointer1 is NULL, then (previous of node of pointer2 + pointer2 -> data)/2.

Example

Program to illustrate the working of our solution

#include <bits/stdc++.h>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void findMedianValue(Node* head){
   Node* ptr1 = head;
   Node* ptr2 = head;
   Node* prev = head;
   if (head != NULL) {
      while (ptr2 != NULL && ptr2->next != NULL) {
         ptr2 = ptr2->next->next;
         prev = ptr1;
         ptr1 = ptr1->next;
      }
      if (ptr2 != NULL)
         cout<<ptr1->data;
      else
         cout<<float(ptr1->data + prev->data) / 2;
   }
}
void pushVal(struct Node** head_ref, int new_data){
   Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = (*head_ref);
   (*head_ref) = new_node;
}
int main(){
   struct Node* head = NULL;
   pushVal(&head, 3);
   pushVal(&head, 5);
   pushVal(&head, 6);
   pushVal(&head, 8);
   pushVal(&head, 9);
   pushVal(&head, 11);
   cout<<"The median of the linked list is ";
   findMedianValue(head);
   return 0;
}

Output

The median of the linked list is 7
raja
Updated on 01-Feb-2022 10:05:39

Advertisements