leetcode之hot100---21合并两个有序链表(C++)

思路一:暴力解法

分别遍历两个链表,不断比较节点大小,将较小的放入新链表

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* list1, ListNode* list2) {
        //声明一个新链表的哨兵节点,并初始化其值为-1,其后继为空
        ListNode* list3 = new ListNode(-1);
        //构建三个指针分别指向链表1、链表2、新链表
        ListNode* p1 = list1;
        ListNode* p2 = list2;
        ListNode* p3 = list3;
        //当两链表均未遍历完,继续合并
        while(p1 != nullptr && p2 != nullptr){
            //将较小值优先放入新链表中
            if(p1->val < p2->val){
                p3->next = p1;
                p1 = p1->next;
            }
            else{
                p3->next = p2;
                p2 = p2->next;
            }
            p3 = p3->next;
        }
        //将还未遍历完的链表直接与新链表的尾部连接起来
        if(p1 != nullptr){
            p3->next = p1;
        }
        if(p2 != nullptr){
            p3->next = p2;
        }
        //返回新链表头结点的后继
        return list3->next;
    }
};
  • 时间复杂度:O(n+m)
  • 空间复杂度:O(1)

思路二:递归

cpp 复制代码
class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if (l1 == nullptr) {
            return l2;
        } else if (l2 == nullptr) {
            return l1;
        } else if (l1->val < l2->val) {
            l1->next = mergeTwoLists(l1->next, l2);
            return l1;
        } else {
            l2->next = mergeTwoLists(l1, l2->next);
            return l2;
        }
    }
};
  • 时间复杂度:O(n+m)
  • 空间复杂度:O(n+m)
相关推荐
哥不想学算法3 小时前
【C++】字符串字面量拼接
开发语言·c++
海石3 小时前
1500分的题目,确实有实力,不过还是我略胜一筹
算法·leetcode
海石3 小时前
【记忆化搜索】条条大路通AC,走好适合你的那一条,走到后再考虑走得快
算法·leetcode
gugucoding6 小时前
31. 【C语言】堆栈与队列的实现
c语言·开发语言·数据结构·链表
ChaoZiLL7 小时前
我的数据结构3——链表(link list)
数据结构·链表
cookies_s_s8 小时前
C++ 字符串动态创建对象 -- 工厂模式、自动注册、模板递归动态调用
服务器·开发语言·c++
王老师青少年编程9 小时前
2026年6月GESP真题及题解(C++七级):消消乐
数据结构·c++·算法·真题·gesp·2026年6月
海清河晏1119 小时前
数据结构 | 二叉搜索树
数据结构·c++·visual studio
盐焗鹌鹑蛋9 小时前
【C++】继承
开发语言·c++
会周易的程序员10 小时前
使用 pybind11 封装 C++ 日志库 microLog 为 Python 模块
java·c++·python·物联网·架构·日志·aiot