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;
    }
};
相关推荐
1000世界小札6 小时前
《大话数据结构》第9章精读:归并排序与快速排序完整 C++ 实现
数据结构·c++·算法
2601_956121979 小时前
背包基础篇(01、完全、分组、多重、混合)
c++·算法·动态规划
fpcc9 小时前
跟我学C++中级篇——编译期的条件选择
开发语言·c++
兴通物联科技10 小时前
SMT PCB 微小 DataMatrix 码扫不动问题分析 兴通 XT8601B 600 万像素工业读码器落地实践
大数据·人工智能·单片机·嵌入式硬件·算法·计算机视觉
月华路12 小时前
G1 GC 对数组与大对象(Humongous)的处理
java·jvm·算法
我想走路带风12 小时前
LRU和最长前缀和(计算机网络算法)
计算机网络·算法
M78佐菲13 小时前
Linux学习笔记:进程
linux·笔记·学习·算法
ShineWinsu13 小时前
对于C++:C++20中线程、初始化、Lambda与内存视图等特性的解析
c++·c++20
徐小夕14 小时前
表格、文档、甘特、大屏、表单一站打通:pxcharts超级表格4.0正式上线!
前端·算法·github