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;
    }
};
相关推荐
Mr_Xuhhh9 分钟前
LeetCode hot 100(C++版本)(上)
c++·leetcode·哈希算法
漫随流水14 分钟前
c++编程:反转字符串(leetcode344)
数据结构·c++·算法
南境十里·墨染春水41 分钟前
C++ 笔记 友元(面向对象)
开发语言·c++·笔记
C++ 老炮儿的技术栈1 小时前
分享一个安全的CString
c语言·c++·windows·git·安全·visual studio
穿条秋裤到处跑2 小时前
每日一道leetcode(2026.03.31):字典序最小的生成字符串
算法·leetcode
桦02 小时前
[C++复习]:STL
开发语言·c++
苏宸啊3 小时前
rbtree封装map和set
c++
汉克老师3 小时前
GESP2025年6月认证C++三级( 第一部分选择题(1-8))
c++·二进制·原码·补码·gesp三级·gesp3级·八进制、
不想写代码的星星3 小时前
C++ 折叠表达式:“我写递归你写折叠,咱俩代码差十年”
c++
CoovallyAIHub4 小时前
VisionClaw:智能眼镜 + Gemini + Agent,看一眼就能帮你搜、帮你发、帮你做
算法·架构·github