LeetCode21. Merge Two Sorted Lists

文章目录

一、题目

You are given the heads of two sorted linked lists list1 and list2.

Merge the two lists into one sorted list. The list should be made by splicing together the nodes of the first two lists.

Return the head of the merged linked list.

Example 1:

Input: list1 = 1,2,4, list2 = 1,3,4

Output: 1,1,2,3,4,4

Example 2:

Input: list1 = \[\], list2 = \[\]

Output: \[\]

Example 3:

Input: list1 = \[\], list2 = 0

Output: 0

Constraints:

The number of nodes in both lists is in the range 0, 50.

-100 <= Node.val <= 100

Both list1 and list2 are sorted in non-decreasing order.

二、题解

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) {
        if(list1 == nullptr) return list2;
        if(list2 == nullptr) return list1;
        ListNode* head = list1->val < list2->val ? list1 : list2;
        ListNode* cur1 = head->next;
        ListNode* cur2 = head == list1 ? list2:list1;
        ListNode* pre = head;
        while(cur1 && cur2){
            if(cur1->val < cur2->val){
                pre->next = cur1;
                cur1 = cur1->next;
            }
            else{
                pre->next = cur2;
                cur2 = cur2->next;
            }
            pre = pre->next;
        }
        pre->next = cur1 != nullptr ? cur1:cur2;
        return head;
    }
};
相关推荐
起个名字费劲死了1 分钟前
VisionMaster 十二点标定+单点抓取
c++·visionmaster
Interview Aid1126 分钟前
Stripe VO 面经汇总:5 轮面试题目与考察重点
算法
EEET智选11 分钟前
科技晨间速报 | AI 安全警钟、开源新模型与苹果智能家居
人工智能·科技·算法·机器学习·ai
挖掘狂人23 分钟前
哈希算法:一根看不见的 "指纹",如何撑起整个互联网
算法·程序员·掘金技术征文
鶴哥只手遮天32 分钟前
ecRad 1.5.0 算法原理详解
算法·开源
不会就选b1 小时前
算法日常・每日刷题--<动态规划>22
算法·动态规划
释厄6231 小时前
字画同体论——字即画·几何即字·漫画与小说=文本层
人工智能·算法
沫璃染墨1 小时前
从零入门数据结构与算法(一):复杂度分析——从算法效率到时间与空间复杂度
c语言·开发语言·数据结构·笔记·算法·飞书
熊猫钓鱼>_>2 小时前
面试出现 606 次的第 K 大,被拆成三个问题问
算法·面试·职场和发展·校招·面经·oj·ai生成
Lzg_na2 小时前
僵尸进程、孤儿进程、守护进程:含义、区别与生命周期详解
c++