C++ program to find the second largest element in a Linked list

In this article, we will learn to find the second largest element in a Linked list in C++. A linked list is a linear collection of data(nodes) that are stored randomly in the memory. In liked list, each node has two components one is data and the other is a link to the next node.

Examples

```Input: 34 -> 2 -> 4 -> 12 -> 67 ->5
Output: 34

Input: 1 -> 2 -> 3 -> 4
Output: 3```

Finding the second largest element in a Linked list in C++

1. Declare two variables maxi and sec_max and store the maximum and minimum value between the first two nodes respectively.

2. Traverse the given linked list for each node check

• If the current node data is greater than the maxi then set sec_max as maxi and maxi as current node data.
• If the current node data is greater than the sec_node then set sec_max as current node data.

3. Finally, return the sec_max value.

```#include <bits/stdc++.h>
using namespace std;
struct Node{
int data;
struct Node* next;
};
// fucntion to insert new node at the begining of the linked list
Node* new_node = new Node;
new_node->data = data;
}
// function to print the list
{
}
}
// function to find the second largest element
int maxi = max(v1, v1);
int sec_max = min(v1, v2);
sec_max = maxi;
}
}
}
return sec_max;
}
int main(){
```The given linked list is: 62 5 42 89 12 3