이 튜토리얼에서는 주어진 연결 리스트로부터 새로운 연결 리스트를 생성하는 프로그램을 작성할 것입니다.
우리는 크기가 같은 두 개의 연결 목록을 제공했으며 두 연결 목록의 최대 수를 사용하여 두 연결 목록에서 새 연결 목록을 만들어야 합니다.
문제를 해결하는 단계를 살펴보겠습니다.
-
구조체 노드를 작성하십시오.
-
크기가 같은 두 개의 연결 목록을 만듭니다.
-
연결 목록을 반복합니다.
-
두 개의 연결 리스트 노드에서 최대 수를 찾습니다.
-
최대 개수의 새 노드를 생성합니다.
-
새 연결 목록에 새 노드를 추가합니다.
-
-
새 연결 목록을 인쇄합니다.
예시
코드를 봅시다.
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
void insertNewNode(Node** root, int item) {
Node *ptr, *temp;
temp = new Node;
temp->data = item;
temp->next = NULL;
if (*root == NULL) {
*root = temp;
}
else {
ptr = *root;
while (ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = temp;
}
}
void printLinkedList(Node* root) {
while (root != NULL) {
cout << root->data << " -> ";
root = root->next;
}
cout << "NULL" << endl;
}
Node* generateNewLinkedList(Node* root1, Node* root2) {
Node *ptr1 = root1, *ptr2 = root2;
Node* root = NULL;
while (ptr1 != NULL) {
int currentMax = ((ptr1->data < ptr2->data) ? ptr2->data : ptr1->data);
if (root == NULL) {
Node* temp = new Node;
temp->data = currentMax;
temp->next = NULL;
root = temp;
}
else {
insertNewNode(&root, currentMax);
}
ptr1 = ptr1->next;
ptr2 = ptr2->next;
}
return root;
}
int main() {
Node *root1 = NULL, *root2 = NULL, *root = NULL;
insertNewNode(&root1, 1);
insertNewNode(&root1, 2);
insertNewNode(&root1, 3);
insertNewNode(&root1, 4);
insertNewNode(&root2, 3);
insertNewNode(&root2, 1);
insertNewNode(&root2, 2);
insertNewNode(&root2, 4);
root = generateNewLinkedList(root1, root2);
printLinkedList(root);
return 0;
} 출력
위의 코드를 실행하면 다음과 같은 결과를 얻을 수 있습니다.
3 -> 2 -> 3 -> 4 -> NULL
결론
튜토리얼에서 질문이 있는 경우 댓글 섹션에 언급하세요.