当前位置:网站首页>【LeetCode】21. 合并两个有序链表
【LeetCode】21. 合并两个有序链表
2022-07-31 10:03:00 【酥酥~】
题目
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4]
输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = []
输出:[]
示例 3:
输入:l1 = [], l2 = [0]
输出:[0]
提示:
两个链表的节点数目范围是 [0, 50]
-100 <= Node.val <= 100
l1 和 l2 均按 非递减顺序 排列
题解
新建一个链表
从头遍历两个链表,值较小的结点放入新链表中
/** * 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) {
ListNode* result = new ListNode();
ListNode* tmp = result;
while(list1 && list2)
{
if(list1->val <= list2->val)
{
tmp->next = list1;
list1 = list1->next;
}
else
{
tmp->next = list2;
list2 = list2->next;
}
tmp = tmp->next;
}
tmp->next = list1 ? list1 :list2;
return result->next;
}
};
使用递归方法
/** * 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;
if(list1->val <= list2->val)
{
list1->next = mergeTwoLists(list1->next,list2);
return list1;
}
else
{
list2->next = mergeTwoLists(list1,list2->next);
return list2;
}
}
};
边栏推荐
- Mybaits Frequently Asked Questions Explained
- The fifth chapter
- odoo14 | 附件上传功能及实际使用
- SQLite3交叉编译
- Flink1.15 source code reading flink-clients - flink command line help command
- 让动画每次重复前都有延迟
- js department budget and expenditure radar chart
- 业务-(课程-章节-小节)+课程发布一些业务思路
- 尚医通【预约挂号系统】总结
- What is the encoding that starts with ?
猜你喜欢
开放麒麟 openKylin 自动化开发者平台正式发布
出色的移动端用户验证
WEB核心【记录网站登录人数,记录用户名案例】Cookie技术实现
Mysql+Navicat for Mysql
感情危机,朋友的网恋女友要和他闹分手,问我怎么办
NowCoderTOP28-34 binary tree - continuous update ing
Implement a thread pool
Android安全专题(三)JNI混淆
Gradle系列——Groovy概述,基础使用(基于Groovy文档4.0.4)day2-1
Are postgresql range queries faster than index queries?
随机推荐
postgresql 生成随机日期,随机时间
感情危机,朋友的网恋女友要和他闹分手,问我怎么办
Come n times with the sword--05. Replace spaces
VMware下安装win10启动后进入Boot Manger界面如何解决
Come n times - 09. Implement queues with two stacks
湖仓一体电商项目(二):项目使用技术及版本和基础环境准备
业务-(课程-章节-小节)+课程发布一些业务思路
Scala基础【seq、set、map、元组、WordCount、队列、并行】
Dart Log tool class
混合型界面:对话式UI的未来
Android安全专题(三)JNI混淆
NowCoderTOP28-34二叉树——持续更新ing
学习笔记——七周成为数据分析师《第二周:业务》:业务分析框架
Dart Log工具类
win10镜像下载
数据中台建设(六):数据体系建设
浏览器使用占比js雷达图
富文本编辑器Tinymce
ReentrantLock
二叉树的搜索与回溯问题(leetcode)