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;
    }
};
相关推荐
腾讯云开发者4 分钟前
数据与 AI 双向奔赴,腾讯云架构师技术沙龙精彩回顾
数据结构
快手技术15 分钟前
快手 & 南大发布代码智能“指南针”,重新定义 AI 编程能力评估体系
算法
Murphy_lx29 分钟前
C++ std_stringstream
开发语言·c++·算法
xiaoxue..39 分钟前
栈的全面解析:ADT、实现与应用
javascript·数据结构·面试
Mr.Winter`42 分钟前
基于Proto3和单例模式的系统参数配置模块设计(附C++案例实现)
c++·人工智能·单例模式·机器人
CoovallyAIHub1 小时前
超越YOLOv8/v11!自研RKM-YOLO为输电线路巡检精度、速度双提升
深度学习·算法·计算机视觉
哭泣方源炼蛊1 小时前
HAUE 新生周赛(七)题解
数据结构·c++·算法
q***64972 小时前
SpringMVC 请求参数接收
前端·javascript·算法
Lwcah2 小时前
Python | LGBM+SHAP可解释性分析回归预测及可视化算法
python·算法·回归
小此方2 小时前
从零开始手搓堆:核心操作实现 + 堆排序 + TopK 算法+ 向上调整 vs 向下调整建堆的时间复杂度严密证明!
开发语言·数据结构·算法