Find the Second Largest Element in a Linked List in C++

C++Server Side ProgrammingProgramming

Here we will see the second largest element in the linked list. Suppose there are n different nodes with numerical values. So if the list is like [12, 35, 1, 10, 34, 1], then second largest element will be 34.

This process is similar to the finding of second largest element in an array, we will traverse through the list and find second largest element by comparing.

Example

#include<iostream>
using namespace std;
class Node {
   public:
      int data;
      Node *next;
};
void prepend(Node** start, int new_data) {
   Node* new_node = new Node;
   new_node->data = new_data;
   new_node->next = NULL;
   if ((*start) != NULL){
      new_node->next = (*start);
      *start = new_node;
   }
   (*start) = new_node;
}
int secondLargestElement(Node *start) {
   int first_max = INT_MIN, second_max = INT_MIN;
   Node *p = start;
   while(p != NULL){
      if (p->data > first_max) {
         second_max = first_max;
         first_max = p->data;
      }else if (p->data > second_max)
         second_max = p->data;
         p = p->next;
   }
   return second_max;
}
int main() {
   Node* start = NULL;
   prepend(&start, 15);
   prepend(&start, 16);
   prepend(&start, 10);
   prepend(&start, 9);
   prepend(&start, 7);
   prepend(&start, 17);
   cout << "Second largest element is: " << secondLargestElement(start);
}

Output

Second largest element is: 16
raja
Published on 19-Dec-2019 17:26:44
Advertisements