Ở đây ta sẽ thấy phần tử lớn thứ hai trong danh sách liên kết. Giả sử có n nút khác nhau với giá trị số. Nếu danh sách như [12, 35, 1, 10, 34, 1], phần tử lớn thứ hai sẽ là 34.
Quy trình này tương tự tìm phần tử lớn thứ hai trong mảng, ta duyệt qua danh sách và tìm lớn thứ hai bằng cách so sánh.
Ví dụ mã nguồn
#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); } Kết quả
Second largest element is: 16