C代码
/**
* Definition for singly-linked list.
* struct ListNode {
*int val;
*struct ListNode *next;
* };
*/struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
struct ListNode *dummy = NULL;
struct ListNode *head = NULL;
if (list1 == NULL) {
return list2;
}if (list2 == NULL) {
return list1;
}if(list1->val <= list2->val) {
dummy = list1;
list1 = list1->next;
} else {
dummy = list2;
list2 = list2->next;
}
head = dummy;
while(list1 != NULL && list2 != NULL) {
if (list1->val >= list2->val) {
dummy->next = list2;
list2 = list2->next;
} else {
dummy->next = list1;
list1 = list1->next;
}
dummy = dummy->next;
}
if (list1 != NULL) {
dummy->next = list1;
}
if (list2 != NULL) {
dummy->next = list2;
}
return head;
}
注意点
dummy和head
节点的初始化,需要移动list1或者list2;- 遍历操作感觉比较冗余(头初始化list1或者list2,后去遍历代码又移动一次),代码需要优化;
文章图片
DUMMY C代码优化版本
/**
* Definition for singly-linked list.
* struct ListNode {
*int val;
*struct ListNode *next;
* };
*/struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2){
struct ListNode *dummy = NULL;
struct ListNode *head = NULL;
if (list1 == NULL) {
return list2;
}if (list2 == NULL) {
return list1;
}head = calloc(1, sizeof(struct ListNode));
dummy = head;
while(list1 != NULL && list2 != NULL) {
if (list1->val >= list2->val) {
dummy->next = list2;
list2 = list2->next;
} else {
dummy->next = list1;
list1 = list1->next;
}
dummy = dummy->next;
}
if (list1 != NULL) {
dummy->next = list1;
}
if (list2 != NULL) {
dummy->next = list2;
}
dummy = head->next;
free(head);
head = NULL;
return dummy;
}
思路
- 新建头节点空间
head
; - 最终返回
head->next
,来统一list1与list2的移动逻辑到while循环内
;
文章图片
推荐阅读
- 安全|第一篇关于我的个人博客--与诸君共勉
- python|第一篇博客,与您共勉
- 蓝桥杯|蓝桥杯python(题目思路即解答(笔记,持续更新))
- 算法|第十届蓝桥杯省赛B组题解记录
- 算法与数据结构|第十届蓝桥杯大赛软件类省赛Java研究生组-题解
- 蓝桥杯|第十届蓝桥杯省赛编程题题解(C++A组)
- 蓝桥杯|第八届蓝桥杯省赛代码+题解
- LeetCode|LeetCode1143. 最长公共子序列
- 算法|蓝桥 小明的游戏1 博弈论 nim