Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

โปรแกรม C++ หาองค์ประกอบที่ใหญ่เป็นอันดับสองใน Linked List


ที่นี่เราจะดูองค์ประกอบที่ใหญ่เป็นอันดับสองใน linked list สมมติว่ามี n โหนดที่แตกต่างกันด้วยค่าตัวเลข ดังนั้นถ้ารายการเป็นเช่น [12, 35, 1, 10, 34, 1] องค์ประกอบที่ใหญ่เป็นอันดับสองจะเป็น 34

กระบวนการนี้คล้ายกับการหาองค์ประกอบที่ใหญ่เป็นอันดับสองในอาร์เรย์ เราจะเดินทางผ่านรายการและหาองค์ประกอบที่ใหญ่เป็นอันดับสองโดยการเปรียบเทียบ

ตัวอย่างโค้ด C++

#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