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)
相关推荐
SNAKEpc121381 小时前
Qt开源控件库(qt-material-widgets)的编译及使用
c++·qt·开源
轩宇^_^3 小时前
C++ 类与对象的实际应用案例详解
开发语言·c++
c7_ln4 小时前
编程视界:C++命名空间
开发语言·c++·笔记
十五年专注C++开发4 小时前
SQLiteStudio:一款免费开源跨平台的SQLite管理工具
数据库·c++·qt·sqlite
Serendipity-Solitude4 小时前
c++中的数学函数库(少)
开发语言·c++
坚定学代码4 小时前
PIMPL模式
c++
imgsq4 小时前
已安装 MFC 仍提示“此项目需要 MFC 库”的解决方法 (MSB8041)
c++·mfc
香菇滑稽之谈5 小时前
责任链模式的C++实现示例
开发语言·c++·设计模式·责任链模式
蜕变的土豆5 小时前
二、重学C++—C语言核心
c语言·c++