ที่นี่เราจะเห็นองค์ประกอบที่ใหญ่เป็นอันดับสองในรายการที่เชื่อมโยง สมมติว่ามีโหนดที่แตกต่างกัน n ที่มีค่าตัวเลข ดังนั้นหากรายการเป็นเช่น [12, 35, 1, 10, 34, 1] องค์ประกอบที่ใหญ่เป็นอันดับสองจะเป็น 34
กระบวนการนี้คล้ายกับการค้นหาองค์ประกอบที่ใหญ่เป็นอันดับสองในอาร์เรย์ เราจะสำรวจผ่านรายการและค้นหาองค์ประกอบที่ใหญ่เป็นอันดับสองโดยการเปรียบเทียบ
ตัวอย่าง
#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);
} ผลลัพธ์
Second largest element is: 16