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;
    }
};
相关推荐
用户686916134903 分钟前
1999年NOIP普及组旅行家的预算(洛谷P1016):贪心算法实战指南
c++
程序员编程指南39 分钟前
Qt 与 WebService 交互开发
c语言·开发语言·c++·qt·交互
荼蘼42 分钟前
基于 KNN 算法的手写数字识别项目实践
人工智能·算法·机器学习
溟洵1 小时前
Qt 窗口 工具栏QToolBar、状态栏StatusBar
开发语言·前端·数据库·c++·后端·qt
Yuroo zhou1 小时前
IMU的精度对无人机姿态控制意味着什么?
单片机·嵌入式硬件·算法·无人机·嵌入式实时数据库
铭哥的编程日记1 小时前
《C++ list 完全指南:list的模拟实现》
c++
程序员编程指南1 小时前
Qt 远程过程调用(RPC)实现方案
c语言·c++·qt·rpc·系统架构
jackzhuoa2 小时前
java小白闯关记第一天(两个数相加)
java·算法·蓝桥杯·期末
Codeking__3 小时前
链表算法综合——重排链表
网络·算法·链表
minji...3 小时前
数据结构 堆(4)---TOP-K问题
java·数据结构·算法