In this tutorial, we are going to write a program that finds the triplet in the linked list whose sum is equal to the given number.
Let's see the steps to solve the problem.
Create a struct node for the linked list.
Create the linked list with dummy data.
Write three inner loops for three elements which iterate until the end of the linked list.
Add the three elements.
Compare the sum with the given number.
If both are equal, then print the elements and break the loops.
Example
Let's see the code.
#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;
}Output
If you run the above code, then you will get the following result.
1 4 4 No triplet found
Conclusion
If you have any queries in the tutorial, mention them in the comment section.