이 튜토리얼에서는 연결 리스트에서 주어진 숫자와 합이 같은 트리플렛을 찾는 프로그램을 작성할 것입니다.
문제를 해결하는 단계를 살펴보겠습니다.
-
연결 목록에 대한 구조체 노드를 만듭니다.
-
더미 데이터로 연결 리스트를 생성합니다.
-
연결 목록이 끝날 때까지 반복되는 세 개의 요소에 대해 세 개의 내부 루프를 작성하십시오.
-
세 가지 요소를 추가합니다.
-
합을 주어진 숫자와 비교하십시오.
-
둘 다 같으면 요소를 인쇄하고 루프를 끊습니다.
-
예시
코드를 봅시다.
#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
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.