Finding Median in a Sorted Linked List

Given A sorted linked list of N 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:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find median
// of a linked list
#include <bits/stdc++.h>
using namespace std;
  
// Link list node
struct Node {
    int data;
    struct Node* next;
};
  
/* Function to get the median of the linked list */
void printMidean(Node* head)
{
    Node* slow_ptr = head;
    Node* fast_ptr = head;
    Node* pre_of_slow = head;
  
    if (head != NULL) {
        while (fast_ptr != NULL && fast_ptr->next != NULL) {
  
            fast_ptr = fast_ptr->next->next;
  
            // previous of slow_ptr
            pre_of_slow = slow_ptr;
            slow_ptr = slow_ptr->next;
        }
  
        // if the below condition is true linked list
        // contain odd Node
        // simply return middle element
        if (fast_ptr != NULL)
            cout << "Median is : " << slow_ptr->data;
  
        // else linked list contain even element
        else
            cout << "Median is : "
                 << float(slow_ptr->data + pre_of_slow->data) / 2;
    }
}
  
/* Given a reference (pointer to 
    pointer) to the head of a list 
    and an int, push a new node on 
    the front of the list. */
void push(struct Node** head_ref, int new_data)
{
    // allocate node
    Node* new_node = new Node;
  
    // put in the data
    new_node->data = new_data;
  
    // link the old list
    // off the new node
    new_node->next = (*head_ref);
  
    // move the head to point
    // to the new node
    (*head_ref) = new_node;
}
  
// Driver Code
int main()
{
    // Start with the
    // empty list
    struct Node* head = NULL;
  
    // Use push() to construct
    // below list
    // 1->2->3->4->5->6
    push(&head, 6);
    push(&head, 5);
    push(&head, 4);
    push(&head, 3);
    push(&head, 2);
    push(&head, 1);
  
    // Check the count
    // function
    printMidean(head);
  
    return 0;
}

chevron_right


Java

filter_none

edit
close

play_arrow

link
brightness_4
code

// Java program to find median
// of a linked list
class GFG 
{
  
    // Link list node
    static class Node
    {
  
        int data;
        Node next;
    };
  
    /* Function to get the median of the linked list */
    static void printMidean(Node head)
    {
        Node slow_ptr = head;
        Node fast_ptr = head;
        Node pre_of_slow = head;
  
        if (head != null
        {
            while (fast_ptr != null && fast_ptr.next != null
            {
  
                fast_ptr = fast_ptr.next.next;
  
                // previous of slow_ptr
                pre_of_slow = slow_ptr;
                slow_ptr = slow_ptr.next;
            }
  
            // if the below condition is true linked list
            // contain odd Node
            // simply return middle element
            if (fast_ptr != null)
            {
                System.out.print("Median is : " + slow_ptr.data);
            }
              
            // else linked list contain even element
            else 
            {
                System.out.print("Median is : "
                        + (float) (slow_ptr.data + pre_of_slow.data) / 2);
            }
        }
    }
  
    /* Given a reference (pointer to 
    pointer) to the head of a list 
    and an int, push a new node on 
    the front of the list. */
    static Node push(Node head_ref, int new_data)
    {
        // allocate node
        Node new_node = new Node();
  
        // put in the data
        new_node.data = new_data;
  
        // link the old list
        // off the new node
        new_node.next = head_ref;
  
        // move the head to point
        // to the new node
        head_ref = new_node;
        return head_ref;
    }
  
    // Driver Code
    public static void main(String[] args) 
    {
        // Start with the
        // empty list
        Node head = null;
  
        // Use push() to construct
        // below list
        // 1.2.3.4.5.6
        head = push(head, 6);
        head = push(head, 5);
        head = push(head, 4);
        head = push(head, 3);
        head = push(head, 2);
        head = push(head, 1);
  
        // Check the count
        // function
        printMidean(head);
    }
}
  
// This code is contributed by PrinciRaj1992

chevron_right


C#

filter_none

edit
close

play_arrow

link
brightness_4
code

// C# program to find median
// of a linked list
using System;
  
class GFG 
{
  
    // Link list node
    class Node
    {
  
        public int data;
        public Node next;
    };
  
    /* Function to get the median 
    of the linked list */
    static void printMidean(Node head)
    {
        Node slow_ptr = head;
        Node fast_ptr = head;
        Node pre_of_slow = head;
  
        if (head != null
        {
            while (fast_ptr != null && 
                   fast_ptr.next != null
            {
                fast_ptr = fast_ptr.next.next;
  
                // previous of slow_ptr
                pre_of_slow = slow_ptr;
                slow_ptr = slow_ptr.next;
            }
  
            // if the below condition is true linked list
            // contain odd Node
            // simply return middle element
            if (fast_ptr != null)
            {
                Console.Write("Median is : "
                               slow_ptr.data);
            }
              
            // else linked list contain even element
            else
            {
                Console.Write("Median is : "
                       (float)(slow_ptr.data + 
                               pre_of_slow.data) / 2);
            }
        }
    }
  
    /* Given a reference (pointer to 
    pointer) to the head of a list 
    and an int, push a new node on 
    the front of the list. */
    static Node push(Node head_ref, int new_data)
    {
        // allocate node
        Node new_node = new Node();
  
        // put in the data
        new_node.data = new_data;
  
        // link the old list
        // off the new node
        new_node.next = head_ref;
  
        // move the head to point
        // to the new node
        head_ref = new_node;
        return head_ref;
    }
  
    // Driver Code
    public static void Main(String[] args) 
    {
        // Start with the
        // empty list
        Node head = null;
  
        // Use push() to construct
        // below list
        // 1->2->3->4->5->6
        head = push(head, 6);
        head = push(head, 5);
        head = push(head, 4);
        head = push(head, 3);
        head = push(head, 2);
        head = push(head, 1);
  
        // Check the count
        // function
        printMidean(head);
    }
  
// This code is contributed by Rajput-Ji

chevron_right


Output:

Median is : 3.5


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : princiraj1992, Rajput-Ji