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

หา Triplet จาก Linked List สามตัวที่มีผลรวมเท่ากับตัวเลขที่กำหนดใน C++

ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่หา triplet ใน linked list ที่ผลรวมเท่ากับตัวเลขที่กำหนด

มาดูขั้นตอนในการแก้ปัญหา

  • สร้าง struct node สำหรับ linked list
  • สร้าง linked list ด้วยข้อมูลจำลอง
  • เขียนลูปซ้อนสามชั้นสำหรับสามองค์ประกอบซึ่งวนจนถึงท้ายของ linked list
    • บวกสามองค์ประกอบ
    • เปรียบเทียบผลรวมกับตัวเลขที่กำหนด
    • ถ้าทั้งสองเท่ากัน ให้พิมพ์องค์ประกอบและหยุดลูป

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

#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* next;
};

void insertNewNode(Node** head_ref, int new_data) {
    Node* new_node = new Node();
    new_node->data = new_data;
    new_node->next = (*head_ref);
    *head_ref = new_node;
}

void findTriplet(Node *head_one, Node *head_two, Node *head_three, int givenNumber) {
    bool is_triplet_found = false;
    Node *a = head_one;
    while (a != NULL) {
        Node *b = head_two;
        while (b != NULL) {
            Node *c = head_three;
            while (c != NULL) {
                int sum = a->data + b->data + c->data;
                if (sum == givenNumber) {
                    cout << a->data << " " << b->data << " " << c->data << endl;
                    is_triplet_found = true;
                    break;
                }
                c = c->next;
            }
            if (is_triplet_found) {
                break;
            }
            b = b->next;
        }
        if (is_triplet_found) {
            break;
        }
        a = a->next;
    }
    if (!is_triplet_found) {
        cout << "No triplet found" << endl;
    }
}

int main() {
    Node* head_one = NULL;
    Node* head_two = NULL;
    Node* head_three = NULL;
    
    insertNewNode(&head_one, 4);
    insertNewNode(&head_one, 3);
    insertNewNode(&head_one, 2);
    insertNewNode(&head_one, 1);
    
    insertNewNode(&head_two, 4);
    insertNewNode(&head_two, 3);
    insertNewNode(&head_two, 2);
    insertNewNode(&head_two, 1);
    
    insertNewNode(&head_three, 1);
    insertNewNode(&head_three, 2);
    insertNewNode(&head_three, 3);
    insertNewNode(&head_three, 4);
    
    findTriplet(head_one, head_two, head_three, 9);
    findTriplet(head_one, head_two, head_three, 100);
    
    return 0;
}

ผลลัพธ์

ถ้าคุณรันโค้ดด้านบน คุณจะได้ผลลัพธ์ดังนี้

1 4 4
No triplet found

สรุป

หากคุณมีคำถามในบทช่วยสอนนี้ ให้ระบุในส่วนความคิดเห็น