不使用这样的函数:ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) 再更新一下代码
时间: 2023-07-23 19:09:00 浏览: 80
好的,以下是不使用mergeTwoLists函数的代码:
```c++
#include <iostream>
#include <fstream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
};
int main() {
ifstream fin("List.in");
int n, m;
fin >> n;
ListNode* l1 = NULL;
ListNode* cur = NULL;
for (int i = 0; i < n; i++) {
int x;
fin >> x;
if (l1 == NULL) {
l1 = new ListNode();
l1->val = x;
cur = l1;
} else {
cur->next = new ListNode();
cur->next->val = x;
cur = cur->next;
}
}
fin >> m;
ListNode* l2 = NULL;
cur = NULL;
for (int i = 0; i < m; i++) {
int x;
fin >> x;
if (l2 == NULL) {
l2 = new ListNode();
l2->val = x;
cur = l2;
} else {
cur->next = new ListNode();
cur->next->val = x;
cur = cur->next;
}
}
fin.close();
ListNode* dummy = new ListNode();
ListNode* cur1 = l1;
ListNode* cur2 = l2;
ListNode* cur = dummy;
while (cur1 && cur2) {
if (cur1->val <= cur2->val) {
cur->next = cur1;
cur1 = cur1->next;
} else {
cur->next = cur2;
cur2 = cur2->next;
}
cur = cur->next;
}
cur->next = cur1 ? cur1 : cur2;
ListNode* res = dummy->next;
ofstream fout("List.out");
while (res) {
fout << res->val << " ";
res = res->next;
}
fout.close();
return 0;
}
```
在这个代码中,我们没有使用mergeTwoLists函数,而是直接在主函数中实现了链表的合并。具体来说,我们首先创建一个dummy节点,然后使用三个指针cur1,cur2和cur来分别指向l1,l2和dummy节点。接下来,我们使用while循环遍历cur1和cur2,将较小的节点插入dummy节点的后面,并将指针向后移动。最后,我们将剩余的节点插入到dummy节点的后面,然后返回dummy的下一个节点作为结果链表。
阅读全文