Find the Second Largest Element in a Linked List - GeeksforGeeks

29 Jun, 2021
Given a Linked list of integer data. The task is to write a program that efficiently finds the second largest element present in the Linked List.Examples:  
Input : List = 12 -> 35 -> 1 -> 10 -> 34 -> 1
Output : The second largest element is 34.

Input : List = 10 -> 5 -> 10
Output : The second largest element is 5.
 
A Simple Solution will be to first sort the linked list in descending order and then print the second element from the sorted linked list. The time complexity of this solution is O(nlogn).A Better Solution is to traverse the Linked list twice. In the first traversal find the maximum element. In the second traversal find the greatest element less than the element obtained in first traversal. The time complexity of this solution is O(n).A more Efficient Solution can be to find the second largest element in a single traversal. Below is the complete algorithm for doing this:  
1) Initialize two variables first and second to INT_MIN as,
   first = second = INT_MIN
2) Start traversing the Linked List,
   a) If the current element in Linked List say list[i] is greater
      than first. Then update first and second as,
      second = first
      first = list[i]
   b) If the current element is in between first and second,
      then update second to store the value of current variable as
      second = list[i]
3) Return the value stored in second node.
Below is the implementation of the above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to print second largest// value in a linked list#include <climits>#include <iostream> using namespace std; // A linked list nodestruct Node {    int data;    struct Node* next;}; // Function to add a node at the// beginning of Linked Listvoid push(struct Node** head_ref, int new_data){    /* allocate node */    struct Node* new_node = (struct Node*)malloc(sizeof(struct 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;} // Function to count size of listint listSize(struct Node* node){    int count = 0;     while (node != NULL) {        count++;         node = node->next;    }     return count;} // Function to print the second// largest elementvoid print2largest(struct Node* head){    int i, first, second;     int list_size = listSize(head);     /* There should be atleast two elements */    if (list_size < 2) {        cout << "Invalid Input";        return;    }     first = second = INT_MIN;     struct Node* temp = head;     while (temp != NULL) {        if (temp->data > first) {            second = first;            first = temp->data;        }         // If current node's data is in between        // first and second then update second        else if (temp->data > second && temp->data != first)            second = temp->data;         temp = temp->next;    }     if (second == INT_MIN)        cout << "There is no second largest element\n";    else        cout << "The second largest element is " << second;} // Driver program to test above functionint main(){    struct Node* start = NULL;     /* The constructed linked list is:     12 -> 35 -> 1 -> 10 -> 34 -> 1 */    push(&start, 1);    push(&start, 34);    push(&start, 10);    push(&start, 1);    push(&start, 35);    push(&start, 12);     print2largest(start);     return 0;}
// Java program to print second largest// value in a linked listclass GFG{     // A linked list nodestatic class Node{    int data;    Node next;}; // Function to add a node at the// beginning of Linked Liststatic 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;} // Function to count size of liststatic int listSize( Node node){    int count = 0;     while (node != null)    {        count++;         node = node.next;    }     return count;} // Function to print the second// largest elementstatic void print2largest( Node head){    int i, first, second;     int list_size = listSize(head);     // There should be atleast two elements /    if (list_size < 2)    {        System.out.print("Invalid Input");        return;    }     first = second = Integer.MIN_VALUE;     Node temp = head;     while (temp != null)    {        if (temp.data > first)        {            second = first;            first = temp.data;        }         // If current node's data is in between        // first and second then update second        else if (temp.data > second && temp.data != first)            second = temp.data;         temp = temp.next;    }     if (second == Integer.MIN_VALUE)        System.out.print( "There is no second largest element\n");    else        System.out.print ("The second largest element is " + second);} // Driver program to test above functionpublic static void main(String args[]){    Node start = null;     // The constructed linked list is:    //12 . 35 . 1 . 10 . 34 . 1    start=push(start, 1);    start=push(start, 34);    start=push(start, 10);    start=push(start, 1);    start=push(start, 35);    start=push(start, 12);     print2largest(start);}} // This code is contributed by Arnab Kundu
# Python3 program to print second largest# value in a linked list # A linked list nodeclass Node :    def __init__(self):        self.data = 0        self.next = None # Function to add a node at the# beginning of Linked Listdef push( head_ref, new_data) :     # allocate node /    new_node = 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 # Function to count size of listdef listSize( node):     count = 0    while (node != None):        count = count + 1         node = node.next         return count # Function to print the second# largest elementdef print2largest( head):     i = 0    first = 0    second = 0     list_size = listSize(head)     # There should be atleast two elements /    if (list_size < 2) :             print("Invalid Input")        return     first = second = -323767    temp = head     while (temp != None):             if (temp.data > first) :            second = first            first = temp.data                 # If current node's data is in between        # first and second then update second        elif (temp.data > second and temp.data != first) :            second = temp.data         temp = temp.next     if (second == -323767) :        print( "There is no second largest element\n")    else:        print ("The second largest element is " , second) # Driver code start = None # The constructed linked list is:# 12 . 35 . 1 . 10 . 34 . 1start = push(start, 1)start = push(start, 34)start = push(start, 10)start = push(start, 1)start = push(start, 35)start = push(start, 12) print2largest(start) # This code is contributed by Arnab Kundu
// C# program to print second largest// value in a linked listusing System; class GFG{     // A linked list nodepublic class Node{    public int data;    public Node next;}; // Function to add a node at the// beginning of Linked Liststatic 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;} // Function to count size of liststatic int listSize( Node node){    int count = 0;     while (node != null)    {        count++;         node = node.next;    }     return count;} // Function to print the second// largest elementstatic void print2largest(Node head){    int first, second;     int list_size = listSize(head);     // There should be atleast two elements    if (list_size < 2)    {        Console.Write("Invalid Input");        return;    }     first = second = int.MinValue;     Node temp = head;     while (temp != null)    {        if (temp.data > first)        {            second = first;            first = temp.data;        }         // If current node's data is in between        // first and second then update second        else if (temp.data > second &&                 temp.data != first)            second = temp.data;         temp = temp.next;    }     if (second == int.MinValue)        Console.Write( "There is no second" +                       " largest element\n");    else        Console.Write("The second largest " +                      "element is " + second);} // Driver Codepublic static void Main(String []args){    Node start = null;     // The constructed linked list is:    //12 . 35 . 1 . 10 . 34 . 1    start = push(start, 1);    start = push(start, 34);    start = push(start, 10);    start = push(start, 1);    start = push(start, 35);    start = push(start, 12);     print2largest(start);}} // This code is contributed by 29AjayKumar
<script>       // JavaScript program to print second largest      // value in a linked list      // A linked list node      class Node {        constructor() {          this.data = 0;          this.next = null;        }      }       // Function to add a node at the      // beginning of Linked List      function push(head_ref, new_data) {        // allocate node        var 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;      }       // Function to count size of list      function listSize(node) {        var count = 0;         while (node != null) {          count++;           node = node.next;        }         return count;      }       // Function to print the second      // largest element      function print2largest(head) {        var first, second;         var list_size = listSize(head);         // There should be atleast two elements        if (list_size < 2) {          document.write("Invalid Input");          return;        }         first = second = -2147483648;         var temp = head;         while (temp != null) {          if (temp.data > first) {            second = first;            first = temp.data;          }           // If current node's data is in between          // first and second then update second          else if (temp.data > second && temp.data != first)          second = temp.data;           temp = temp.next;        }         if (second == -2147483648)        document.write("There is no second" + " largest element<br>");        else        document.write("The second largest " + "element is " + second);      }       // Driver Code      var start = null;       // The constructed linked list is:      //12 . 35 . 1 . 10 . 34 . 1      start = push(start, 1);      start = push(start, 34);      start = push(start, 10);      start = push(start, 1);      start = push(start, 35);      start = push(start, 12);       print2largest(start);       </script>
The second largest element is 34
 
andrew1234
29AjayKumar
Akanksha_Rai
rdtank
Sorting Quiz
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Delete a node in a Doubly Linked List
Given a linked list which is sorted, how will you insert in sorted way
Insert a node at a specific position in a linked list
Circular Linked List | Set 2 (Traversal)
Program to implement Singly Linked List in C++ using class
Swap nodes in a linked list without swapping data
Priority Queue using Linked List
Circular Singly Linked List | Insertion
Real-time application of Data Structures
Insertion Sort for Singly Linked List