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)
相关推荐
_wyt0016 小时前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾9 小时前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you11 小时前
constexpr函数
c++
凡人叶枫11 小时前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫11 小时前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss11 小时前
BRpc使用
c++·rpc
-森屿安年-12 小时前
63. 不同路径 II
c++·算法·动态规划
chase_my_dream12 小时前
Cartographer详细讲解
c++·人工智能·自动驾驶
森G12 小时前
75、服务器源码解析---------云视频服务项目
linux·服务器·网络·c++·qt
碧海蓝天202212 小时前
C++法则24:在标准 C++ 中,没有任何可移植的方式判断指针 T* pt 指向的内存位置是否已经 构造了对象,程序员必须手动跟踪哪些元素已构造。
java·开发语言·c++