当前位置:网站首页>leetcode21.合并两个有序链表
leetcode21.合并两个有序链表
2022-08-11 05:16:00 【FussyCat】
leecode题链接:LeetCode21.合并两个有序链表
题目描述:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 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 均按 非递减顺序 排列
解题思路:
分别使用递归法和迭代法。
以下用C语言实现:
递归法:
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if (l1 == NULL) {
return l2;
} else if (l2 == NULL) {
return l1;
} else if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
迭代法:
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode *head = (struct ListNode *)malloc(sizeof(struct ListNode)); /* 分配链表头 */
struct ListNode *prev = head;
while (l1 != NULL && l2 != NULL) {
if (l1->val < l2->val) {
prev->next = l1;
l1 = l1->next;
} else {
prev->next = l2;
l2 = l2->next;
}
prev = prev->next;
}
prev->next = (l1 == NULL) ? l2 : l1; /* 其一链表为空的情况 */
return head->next;
}
边栏推荐
猜你喜欢
一张图带你解读--如何从零开始学习接口自动化
(3) Construction of a real-time performance monitoring platform (Grafana+Prometheus+Node_explorer+Jmeter)
[ARM] rk3399 mounts nfs error
【网站小白】mySQL数据库异常断开
(三)性能实时监控平台搭建(Grafana+Prometheus+Node_explorer+Jmeter)
【win10+cuda7.5+cudnn6.0安装caffe④】安装pycaffe
(三)Redis 如何进行压测
RK3399上的Tengine实践笔记
阿里云无法远程连接数据库MySQL错误码10060解决办法_转载
Django--20实现Redis支持、上下文以及上下文和接口的交互
随机推荐
[Verilog] I2S Master Test Bench
selenuim使用cookie登录京东
Some common mysql entry exercises
第4章 复合类型-1
Apache Commons OGNL语法说明_翻译
C语言——函数的使用
【转载】CMake 语法 - 详解 CMakeLists.txt
原生态mongo连接查询代码
Delphi7 learning record - demo example
第二篇 DS5 Armv8 样例工程报错之GCC编译
0708作业---商品信息
Solidrun hummingboard制作SD卡
CSDN 社区内容创作规范
QtDataVisualization 数据3D可视化
QT GrabWindow截取屏幕
【Cron】学习:cron 表达式
DS220702-0707作业
(1) Construction of a real-time performance monitoring platform (Grafana+Influxdb+Jmeter)
基于 TF-IDF 文本匹配实战详细教程 数据+代码 可直接运行
利用rand函数随机生成uuid