
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Find the Second Largest Element in a Linked List in C++
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
- Related Articles
- C++ program to find Second Smallest Element in a Linked List
- C# program to find Largest, Smallest, Second Largest, Second Smallest in a List
- Python Program to Find the Largest Element in a Doubly Linked List
- Find the largest node in Doubly linked list in C++
- Find a peak element in Linked List in C++
- Python program to find Largest, Smallest, Second Largest, and Second Smallest in a List?
- Find the second last node of a linked list in single traversal in C++
- Find smallest and largest elements in singly linked list in C++
- Finding the second largest element in BST using C++
- Python program to find the second largest number in a list
- C++ Program to find the second largest element from the array
- How to find the second largest element in a user-input JavaScript array?
- Searching an Element in a Linked List using C++
- Python Program to Find the Second Largest Number in a List Using Bubble Sort
- Find difference between first and second largest array element in Java

Advertisements