#include <iostream> using namespace std;// 定义单链表结构体 struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) { } }; // 定义单链表基本操作函数 class LinkedList { public: // 合并两个有序链表 static ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode dummy(0); ListNode* tail = &dummy; while (l1 && l2) { if (l1->val < l2->val) { tail->next = l1; l1 = l1->next; } else { tail->next = l2; l2 = l2->next; } tail = tail->next; } tail->next = l1 ? l1 : l2; return dummy.next; } }; int main() {// 定义两个有序链表 ListNode* l1 = new ListNode(1); l1->next = new ListNode(2); l1->next->next = new ListNode(4); ListNode* l2 = new ListNode(1); l2->next = new ListNode(3); l2->next->next = new ListNode(4); // 合并两个有序链表 ListNode* mergedList = LinkedList::mergeTwoLists(l1, l2); // 输出结果 while (mergedList) { cout << mergedList->val << " "; mergedList = mergedList->next; } cout << endl; return 0; }该怎么将两个链表变为可输入的
时间: 2024-02-14 15:04:25 浏览: 58
要将两个链表变为可输入的,可以按照以下方式修改代码:
```c++
#include <iostream>
using namespace std;
// 定义单链表结构体
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) { }
};
// 定义单链表基本操作函数
class LinkedList {
public:
// 合并两个有序链表
static ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
{
ListNode dummy(0);
ListNode* tail = &dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
}
else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
tail->next = l1 ? l1 : l2;
return dummy.next;
}
};
int main() {
// 定义两个有序链表,并输入节点的值
ListNode* l1 = nullptr;
ListNode* l2 = nullptr;
int n1, n2;
cin >> n1 >> n2; // 分别输入两个链表的节点个数
for (int i = 0; i < n1; i++) {
int x;
cin >> x;
ListNode* node = new ListNode(x);
if (l1 == nullptr) {
l1 = node;
}
else {
ListNode* cur = l1;
while (cur->next) {
cur = cur->next;
}
cur->next = node;
}
}
for (int i = 0; i < n2; i++) {
int x;
cin >> x;
ListNode* node = new ListNode(x);
if (l2 == nullptr) {
l2 = node;
}
else {
ListNode* cur = l2;
while (cur->next) {
cur = cur->next;
}
cur->next = node;
}
}
// 合并两个有序链表
ListNode* mergedList = LinkedList::mergeTwoLists(l1, l2);
// 输出结果
while (mergedList) {
cout << mergedList->val << " ";
mergedList = mergedList->next;
}
cout << endl;
return 0;
}
```
在修改后的代码中,先输入两个链表的节点个数,然后循环输入每一个节点的值,并根据输入的值构建链表。最后调用合并函数,输出结果。
阅读全文