ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่จะค้นหาแฝดสามในรายการที่เชื่อมโยงซึ่งมีผลรวมเท่ากับจำนวนที่ระบุ
มาดูขั้นตอนการแก้ปัญหากัน
-
สร้างโหนด struct สำหรับรายการที่เชื่อมโยง
-
สร้างรายการที่เชื่อมโยงด้วยข้อมูลจำลอง
-
เขียนลูปภายใน 3 รายการสำหรับองค์ประกอบ 3 รายการซึ่งจะวนซ้ำจนจบรายการที่เชื่อมโยง
-
เพิ่มสามองค์ประกอบ
-
เปรียบเทียบผลรวมกับตัวเลขที่กำหนด
-
หากทั้งคู่เท่ากัน ให้พิมพ์องค์ประกอบและทำลายลูป
-
ตัวอย่าง
มาดูโค้ดกันเลย
#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
บทสรุป
หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น