3/7—21. 合并两个有序链表

代码实现:

方法1:递归 ---->难点

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode *list1, struct ListNode *list2) {
    /*
        1.如果l1为空,返回l2
        2.如果l2为空,返回l1
        3.如果l1的值小于l2,比较l1的next值和l2,并把值赋给l1的下一个;返回l1
        4.反之,比较l1和l2的next值,并把值赋给l2的下一个;返回l2
    */
    if (list1 == NULL) {
        return list2;
    } else if (list2 == NULL) { 
        return list1;
    }
    if (list1->val < list2->val) { 
        list1->next = mergeTwoLists(list1->next, list2);
        return list1;
    } else {
        list2->next = mergeTwoLists(list1, list2->next);
        return list2;
    }
}

方法2:常规解法+设置虚拟头结点

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode* mergeTwoLists(struct ListNode *list1, struct ListNode *list2) {
    if (list1 == NULL) {
        return list2;
    }
    if (list2 == NULL) {
        return list1;
    }
    struct ListNode *head = malloc(sizeof(*head)); // 设置虚拟头结点
    struct ListNode *h = head;
    while (list1 && list2) {
        if (list1->val < list2->val) {
            h->next = list1;
            list1 = list1->next;
        } else {
            h->next = list2;
            list2 = list2->next;
        }
        h = h->next;
        h->next = NULL;
    }
    if (list1) {
        h->next = list1;
    }
    if (list2) {
        h->next = list2;
    }
    struct ListNode *result = head->next;
    head->next = NULL;
    free(head);
    return result;    
}
相关推荐
Nil20827 分钟前
leetcode 49字母异位分组
算法·leetcode·哈希算法
Nil20815 小时前
leetcode 5最长回文子串
算法·leetcode·职场和发展
m0_6745719715 小时前
力扣 hot 100 python
python·算法·leetcode
圣保罗的大教堂16 小时前
leetcode 3727. 最大交替平方和 中等
leetcode
Xin77017 小时前
LeetCode 200. 岛屿数量(DFS 深度优先遍历法)
leetcode
alphaTao1 天前
LeetCode 每日一题 2026/10/12-2026/10/18
算法·leetcode
Cccp.1231 天前
【leetcode】(十三)大数据处理
数据结构·算法·leetcode
Pniubi1 天前
力扣70爬楼梯
数据结构·算法·leetcode
Navigator_Z2 天前
LeetCode //C - 1293. Shortest Path in a Grid with Obstacles Elimination
c语言·算法·leetcode
Nil2082 天前
leetcode 64最小路径和
算法·leetcode·职场和发展