在 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