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;
    }
};
相关推荐
徐行code2 分钟前
std::bind()和lambda的区别
c++
liuyao_xianhui2 分钟前
寻找旋转排序数组中的最小值_优选算法(二分算法)
算法
努力学算法的蒟蒻5 分钟前
day37(12.18)——leetcode面试经典150
算法·leetcode·面试
超级种码14 分钟前
All In AI——DSPy框架,让智能体开发像模型训练一样
大数据·人工智能·算法
LYFlied16 分钟前
【每日算法】LeetCode 79. 单词搜索
前端·算法·leetcode·面试·职场和发展
小老鼠不吃猫17 分钟前
C++20 STL <numbers> 数学常量库
开发语言·c++·c++20
Chrikk18 分钟前
C++20 Concepts 在算子库开发中的应用:从 SFINAE 到类型约束
人工智能·算法·c++20
炽烈小老头24 分钟前
【每天学习一点算法 2025/12/18】对称二叉树
学习·算法
蒙奇D索大28 分钟前
【数据结构】考研408 | 开放定址法精讲:连续探测的艺术与代价
数据结构·笔记·考研·改行学it
User_芊芊君子29 分钟前
【LeetCode经典题解】:二叉树转字符串递归解法的核心逻辑与代码解剖
算法·leetcode·职场和发展