不使用构造函数,再更新一下代码
时间: 2023-12-11 15:06:09 浏览: 32
好的,以下是不使用构造函数的代码:
```c++
#include <iostream>
#include <fstream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
};
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* dummy = new ListNode();
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;
}
cur->next = l1 ? l1 : l2;
return dummy->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* res = mergeTwoLists(l1, l2);
ofstream fout("List.out");
while (res) {
fout << res->val << " ";
res = res->next;
}
fout.close();
return 0;
}
```
在这个代码中,我们没有使用构造函数,而是手动地分配每个节点的空间,并使用指针来访问每个节点的成员变量。在创建新的节点时,我们首先分配节点的空间,然后将节点的值val初始化为给定的值,将节点的指针next初始化为NULL。例如,创建新节点的代码如下:
```c++
if (l1 == NULL) {
l1 = new ListNode();
l1->val = x;
cur = l1;
} else {
cur->next = new ListNode();
cur->next->val = x;
cur = cur->next;
}
```
在这里,如果当前链表为空,我们就分配一个新节点的空间,将节点的值val初始化为x,并将cur指向该节点。否则,我们就在cur的后面插入一个新节点,将该节点的值val初始化为x,并将cur指向该节点。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)