여기에서 연결 목록에서 두 번째로 큰 요소를 볼 수 있습니다. 숫자 값을 가진 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