算法刷题|LeetCode刷题笔记-21.合并两个有序链表

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; }

注意点
  1. dummy和head节点的初始化,需要移动list1或者list2;
  2. 遍历操作感觉比较冗余(头初始化list1或者list2,后去遍历代码又移动一次),代码需要优化;
结果 算法刷题|LeetCode刷题笔记-21.合并两个有序链表
文章图片

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; }

思路
  1. 新建头节点空间head;
  2. 最终返回head->next,来统一list1与list2的移动逻辑到while循环内;
题目 【算法刷题|LeetCode刷题笔记-21.合并两个有序链表】算法刷题|LeetCode刷题笔记-21.合并两个有序链表
文章图片

    推荐阅读