#include <iostream> using namespace std; struct ListNode { int val; ListNode* next; ListNode(int x) : val(x), next(NULL) {} }; ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { ListNode* dummy = new ListNode(0); ListNode* cur = dummy; while (l1 && l2) { if (l1->val <= l2->val) { cur->next = l1; l1 = l1->next; } else { cur->next = l2; l2 = l2->next; } cur = cur->next; } if (l1) { cur->next = l1; } else { cur->next = l2; } return dummy->next; } int main() { ListNode* l1 = new ListNode(1); l1->next = new ListNode(3); l1->next->next = new ListNode(5); ListNode* l2 = new ListNode(2); l2->next = new ListNode(4); l2->next->next = new ListNode(6); ListNode* merged = mergeTwoLists(l1, l2); while (merged) { cout << merged->val << " "; merged = merged->next; } return 0; }将这段代码中的有序表改成可自己输入
时间: 2024-02-07 11:04:19 浏览: 97
使用include <iostream>时一定要加using namespace std
好的,你可以参考以下代码,其中cin输入的数字需要自己输入,每输入一个数字按回车键确认,输入完毕后输入-1结束输入。
```cpp
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* dummy = new ListNode(0);
ListNode* cur = dummy;
while (l1 && l2) {
if (l1->val <= l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if (l1) {
cur->next = l1;
} else {
cur->next = l2;
}
return dummy->next;
}
int main() {
ListNode* l1 = new ListNode(0);
ListNode* l2 = new ListNode(0);
ListNode* cur1 = l1;
ListNode* cur2 = l2;
int num;
cout << "Please enter the numbers for the first linked list: " << endl;
while (cin >> num && num != -1) {
cur1->next = new ListNode(num);
cur1 = cur1->next;
}
cout << "Please enter the numbers for the second linked list: " << endl;
while (cin >> num && num != -1) {
cur2->next = new ListNode(num);
cur2 = cur2->next;
}
ListNode* merged = mergeTwoLists(l1->next, l2->next);
while (merged) {
cout << merged->val << " ";
merged = merged->next;
}
return 0;
}
```
希望能够帮到你!
阅读全文