在 C++ 中查詢三個連結串列中和等於給定數字的三元組
在本教程中,我們將編寫一個程式,該程式查詢連結串列中和等於給定數字的三元組。
讓我們看看解決問題的步驟。
為連結串列建立一個結構節點。
使用虛擬資料建立連結串列。
為三個元素編寫三個內部迴圈,這些迴圈迭代到連結串列的末尾。
新增三個元素。
將總和與給定數字進行比較。
如果兩者相等,則列印元素並中斷迴圈。
示例
讓我們看看程式碼。
#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
結論
如果您在本教程中有任何疑問,請在評論部分中提及。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP