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;    
}
相关推荐
Rain的Java大神之路3 小时前
LeetCode 45 跳跃游戏 II:大厂面试官最爱追问的贪心题,我把骨头给你拆干净了
java·后端·leetcode
让我们一起加油好吗2 天前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试
Rain的Java大神之路2 天前
LeetCode 42「接雨水」:面试官百出不厌的题,一文讲透从暴力到双指针 O(1)
java·后端·leetcode
Navigator_Z4 天前
LeetCode //C - 1320. Minimum Distance to Type a Word Using Two Fingers
c语言·算法·leetcode
wy_hhxx4 天前
[Leetcode] 滑动窗口
算法·leetcode·滑动窗口
AIgorithmGEEK4 天前
算法·哈希表|从“逐个比”到“按 key 算位置”
数据结构·c++·算法·leetcode·hash
Navigator_Z4 天前
LeetCode //C - 1319. Number of Operations to Make Network Connected
c语言·算法·leetcode
Navigator_Z5 天前
LeetCode //C - 1318. Minimum Flips to Make a OR b Equal to c
c语言·算法·leetcode
驭渊的小故事5 天前
LeetCode 33:搜索旋转排序数组——从二分查找到旋转数组的区间判定
算法·leetcode·职场和发展
郝学胜-神的一滴6 天前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio