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;
    }
};
相关推荐
珊瑚里的鱼2 分钟前
【动态规划】买卖股票的最佳时机含手续费
算法·动态规划
cccyi74 分钟前
C++ 面试题整理
c++·面试
FuckPatience20 分钟前
C# 链表元素的引用地址分析
链表·c#
2401_8856651923 分钟前
从零搭建卷积神经网络:基于PyTorch实现MNIST手写数字分类
pytorch·python·神经网络·算法·机器学习·分类·cnn
bIo7lyA8v24 分钟前
算法优化的多层缓存映射与访问调度模型的技术8
算法
先吃饱再说32 分钟前
JavaScript栈和队列:从“冰柜里的雪糕”到“排队打饭”
javascript·数据结构
dongf201933 分钟前
R语言朴素贝叶斯算法---iris数据集
开发语言·算法·数据分析·r语言
小O的算法实验室34 分钟前
2025年KBS,基于强化学习离散状态转移算法+复杂约束下多无人机任务分配
算法
weixin_3077791337 分钟前
从“大海捞针”到“主动推理”:AI如何重塑云原生故障诊断的根因链
开发语言·人工智能·算法·自动化·原型模式
京东云开发者39 分钟前
一键调用!京东云率先上线MiniMax M3
算法