当前位置:网站首页>【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;
}
}
};
边栏推荐
- Flink1.15 source code reading flink-clients - flink command line help command
- 湖仓一体电商项目(二):项目使用技术及版本和基础环境准备
- Flink1.15 source code reading - PER_JOB vs APPLICATION execution process
- 浅谈Attention与Self-Attention,一起感受注意力之美
- Qt compile error: C2228: '.key' must have class/struct/union on the left
- 初识二叉搜索树
- [ 动词词组 ] 合集
- Solve rpc error: code = Unimplemented desc = method CheckLicense not implemented
- Open Kylin openKylin automation developer platform officially released
- The future of the hybrid interface: conversational UI
猜你喜欢
随机推荐
第六章
[ 动词词组 ] 合集
自定义v-drag指令(横向拖拽滚动)
loadrunner-controller-view script与load generator
cocoaPods管理之后工程结构变化
Flink1.15源码阅读——PER_JOB vs APPLICATION执行流程
loadrunner录制问题
我们能做出来数据库吗?
金鱼哥RHCA回忆录:CL210管理OPENSTACK网络--开放虚拟网络(OVN)简介(课后练习)
What is the encoding that starts with ?
作为面试官,关于线程池的问题我一般这样套路...
恋爱期间的赠与能否撤销
解决rpc error: code = Unimplemented desc = method CheckLicense not implemented
Come n times - 07. Rebuild the binary tree
(C语言)程序环境和预处理
ARC在编译和运行做了什么?
js以变量为键
win10镜像下载
【软考软件评测师】2012综合知识历年真题
NowCoderTOP28-34二叉树——持续更新ing








