Given a Linked List, the task is to find the largest and second largest value in a Linked List.
Input: LL = 10 -> 15 -> 5 -> 20 -> 7 -> 9
Largest = 20
Second Largest = 15
Input: LL = 0 -> 5 -> 52 -> 21
Largest = 52
Second Largest = 21
- Store the maximum of first two nodes in a variable max.
- Store the minimum of first two nodes in a variable second_max.
- Iterate over the remaining linked list. For each node:
- If current node value is greater than max, then set second_max as max and max as current node’s value.
- Else if current node value is greater than second_max, then set second_max as current node’s value.
Below is the implementation of the above approach:
Largest = 20 Second Largest = 15
- Time Complexity: In the above approach, as we are iterating over the linked list only once, so the time complexity is O(N).
- Auxiliary Space Complexity: In the above approach, we are not using any extra space apart from a few constant size variables, so Auxiliary space complexity is O(1).
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Find the Second Largest Element in a Linked List
- Find the largest node in Doubly linked list
- Find smallest and largest elements in singly linked list
- Find the largest N digit multiple of N
- Find largest sum of digits in all divisors of n
- Program to find largest element in an array
- C program to Find the Largest Number Among Three Numbers
- Find the sum of last n nodes of the given Linked List
- Find sum of even and odd nodes in a linked list
- Find modular node in a linked list
- Find unique elements in linked list
- Find the first duplicate element in the linked list
- Find the element in a linked list with frequency at least N/3
- Find a peak element in Linked List
- Find extra node in the second Linked list
- Find pairs with given sum in doubly linked list
- Find length of loop in linked list
- Find the product of first k nodes of the given Linked List
- Find length of loop in a Linked List using Map
- Find the product of last N nodes of the given Linked List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.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.