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;    
}
相关推荐
文丑颜不良啊11 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z12 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode
文丑颜不良啊13 小时前
LeetCode2161~2180题目解析
java·leetcode
文丑颜不良啊15 小时前
LeetCode2141~2160题目解析
java·leetcode
Dream it possible!1 天前
LeetCode 面试经典 150_多维动态规划_交错字符串(97_C++_中等)
算法·leetcode·面试·动态规划
心抵鹊1 天前
算法之双指针系列(一)
算法·leetcode
Pniubi1 天前
力扣560.和为k的子数组
算法·leetcode·职场和发展
Pniubi1 天前
力扣438.找到字符串中所有字母异位词
算法·leetcode·职场和发展
文丑颜不良啊2 天前
LeetCode2081~2100题目解析
java·leetcode
文丑颜不良啊2 天前
LeetCode2061~2080题目解析
java·leetcode