একটি লিঙ্কড লিস্টে দ্বিতীয় সর্বোচ্চ (second largest) এলিমেন্ট বের করতে হবে। উদাহরণ: [12, 35, 1, 10, 34, 1] এর দ্বিতীয় সর্বোচ্চ ৩৪।
অ্যারে-এর মতোই ট্রাভার্স করে first_max এবং second_max ট্র্যাক করুন।
উদাহরণ
#include <iostream>
#include <climits>
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 = *start;
*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);
return 0;
}
আউটপুট
Second largest element is: 16