在本教程中,我们将编写一个程序,该程序从给定的链表中创建一个新的链表。
我们给出了两个大小相同的链表,我们必须从两个链表中创建一个新的链表,并从两个链表中获取最大数目。
让我们看看解决问题的步骤。
编写一个struct节点。
创建两个相同大小的链接列表。
遍历链接列表。
从两个链接列表节点中找到最大数量。
创建一个具有最大数量的新节点。
将新节点添加到新的链表中。
打印新的链表。
让我们看一下代码。
#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 << "第一链表: ";
printLinkedList(root1);
insertNewNode(&root2, 0);
insertNewNode(&root2, 5);
insertNewNode(&root2, 2);
insertNewNode(&root2, 6);
cout << "第二个链接列表: ";
printLinkedList(root2);
root = getNewLinkedList(root1, root2);
cout << "新链接列表: ";
printLinkedList(root);
return 0;
}输出结果如果运行上面的代码,则将得到以下结果。
第一链表: 1->2->3->4->NULL 第二个链接列表: 0->5->2->6->NULL 新链接列表: 1->5->3->6->NULL