这里我们将看到链表中的第二大元素。假设有 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 << "第二大元素是: " << secondLargestElement(start);
}输出结果第二大元素是: 16