# Find a triplet from three linked lists with a sum equal to a given number in C++

C++Server Side ProgrammingProgramming

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.

• 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.

Live Demo

#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;
}
bool is_triplet_found = false;
while (a != NULL) {
while (b != NULL) {
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() {
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.