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;    
}
相关推荐
如竟没有火炬5 分钟前
四数相加贰——哈希表
数据结构·python·算法·leetcode·散列表
埃伊蟹黄面1 小时前
模拟算法思想
c++·算法·leetcode
菜鸟233号4 小时前
力扣654 最大二叉树 java实现
java·算法·leetcode
鹿角片ljp5 小时前
力扣144.二叉树前序遍历-递归和迭代
算法·leetcode·职场和发展
好易学·数据结构5 小时前
可视化图解算法73:跳台阶(爬楼梯)
数据结构·算法·leetcode·动态规划·笔试
Tisfy5 小时前
LeetCode 3433.统计用户被提及情况:(大)模拟
linux·算法·leetcode
长安er6 小时前
LeetCode 98. 验证二叉搜索树 解题总结
java·数据结构·算法·leetcode·二叉树·力扣
sin_hielo6 小时前
leetcode 3433
数据结构·算法·leetcode
Swift社区6 小时前
LeetCode 448 - 找到所有数组中消失的数字
算法·leetcode·职场和发展
茶猫_6 小时前
C++学习记录-旧题新做-字符串压缩
c语言·c++·学习·算法·leetcode