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