ในบทช่วยสอนนี้ เราจะเขียนโปรแกรมที่สร้างรายการเชื่อมโยงใหม่จากรายการเชื่อมโยงที่กำหนด
เราได้ให้รายการที่เชื่อมโยงสองรายการที่มีขนาดเท่ากัน และเราต้องสร้างรายการที่เชื่อมโยงใหม่จากรายการที่เชื่อมโยงทั้งสองรายการด้วยจำนวนสูงสุดจากรายการที่เชื่อมโยงทั้งสองรายการ
มาดูขั้นตอนการแก้ปัญหากัน
-
เขียนโหนดโครงสร้าง
-
สร้างรายการเชื่อมโยงสองรายการที่มีขนาดเท่ากัน
-
วนซ้ำในรายการที่เชื่อมโยง
-
ค้นหาจำนวนสูงสุดจากโหนดรายการที่เชื่อมโยงทั้งสองโหนด
-
สร้างโหนดใหม่ด้วยจำนวนสูงสุด
-
เพิ่มโหนดใหม่ในรายการที่เชื่อมโยงใหม่
-
-
พิมพ์รายการเชื่อมโยงใหม่
ตัวอย่าง
มาดูโค้ดกันเลย
#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
บทสรุป
หากคุณมีข้อสงสัยใดๆ ในบทแนะนำ โปรดระบุในส่วนความคิดเห็น