鱼C论坛

 找回密码
 立即注册
查看: 1663|回复: 0

[技术交流] 【朱迪的LeetCode刷题笔记】21. Merge Two Sorted Lists #Easy #C

[复制链接]
发表于 2021-4-7 13:38:38 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x

  1. 21. Merge Two Sorted Lists #Easy


  2. Merge two sorted linked lists and return it as a sorted list. The list should be made by splicing together the nodes of the first two lists.


  3. Example 1:

  4. Input: l1 = [1,2,4], l2 = [1,3,4]
  5. Output: [1,1,2,3,4,4]


  6. Example 2:

  7. Input: l1 = [], l2 = []
  8. Output: []


  9. Example 3:

  10. Input: l1 = [], l2 = [0]
  11. Output: [0]


  12. Constraints:

  13. The number of nodes in both lists is in the range [0, 50].
  14. -100 <= Node.val <= 100
  15. Both l1 and l2 are sorted in non-decreasing order.
复制代码


C
  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. *     int val;
  5. *     struct ListNode *next;
  6. * };
  7. */


  8. struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
  9.     if (l1 == NULL) {
  10.         return l2;
  11.     }
  12.     if (l2 == NULL) {
  13.         return l1;
  14.     }
  15.     struct ListNode* returnNode = malloc(sizeof(struct ListNode));
  16.     if (l2->val < l1->val) {
  17.         returnNode->val = l2->val;
  18.         l2 = l2->next;
  19.         returnNode->next = NULL;
  20.     } else {
  21.         returnNode->val = l1->val;
  22.         l1 = l1->next;
  23.         returnNode->next = NULL;
  24.     }
  25.     struct ListNode* curNode = returnNode;
  26.     while (1) {
  27.         if (l1 == NULL) {
  28.             curNode->next = l2;
  29.             break;
  30.         } else if (l2 == NULL) {
  31.             curNode->next = l1;
  32.             break;
  33.         } else {
  34.             struct ListNode *newNode = malloc(sizeof(struct ListNode));
  35.             if (l2->val < l1->val) {
  36.                 newNode->val = l2->val;
  37.                 l2 = l2->next;
  38.                 newNode->next = NULL;
  39.                 curNode->next = newNode;
  40.                 curNode = newNode;
  41.             } else {
  42.                 newNode->val = l1->val;
  43.                 l1 = l1->next;
  44.                 newNode->next = NULL;
  45.                 curNode->next = newNode;
  46.                 curNode = newNode;
  47.             }
  48.         }
  49.     }
  50.     return returnNode;
  51. }

复制代码


20分钟左右写出来的吧
unknown.png

本帖被以下淘专辑推荐:

小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-6-6 08:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表