题目链接:
参考题解。
问题记录:
对于一个 struct 定义的结构体,如果使用指针了, 如何初始化一个实例?
cpp
struct ListNode {
int val;
struct ListNode *next;
};
这个写法就不行!
struct ListNode *head = {NULL, NULL};
正确的写法是:
struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode));
完整代码
cpp
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
// 参考题解。
// https://leetcode.cn/problems/merge-two-sorted-lists/solutions/1734801/by-elegant-franklin6qn-mo0y/?envType=study-plan-v2&envId=selected-coding-interview
struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
// struct ListNode *head = {NULL, NULL};
struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *dummy = head;
while (true) {
if (!list1) {
dummy->next = list2;
break;
}
if (!list2) {
dummy->next = list1;
break;
}
if (list1->val < list2->val) {
dummy->next = list1;
list1 = list1->next;
} else {
dummy->next = list2;
list2 = list2->next;
}
dummy = dummy->next;
}
return head->next;
}