当前位置:网站首页>【Hot100】21. 合并两个有序链表
【Hot100】21. 合并两个有序链表
2022-07-02 18:54:00 【王六六的IT日常】
21. 合并两个有序链表
简单题
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
递归
发现有意思的一个图哈哈哈哈哈
- 终止条件:当两个链表都为空时
- 如何递归:我们判断list1 和 list2 的头结点哪个更小,然后较小结点的 next 指针指向其余结点的合并结果。(调用递归)
- 如果 list1 的 val 值更小,则将 list1 .next 与排序好的链表头相接,list2同理
- 返回值:每一层调用都返回排序好的链表头
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */
class Solution {
public ListNode mergeTwoLists(ListNode list1, ListNode list2) {
if (list1 == null) {
return list2;
}
else if (list2 == null) {
return list1;
}
else if (list1.val < list2.val) {
list1.next = mergeTwoLists(list1.next, list2);
return list1;
}
else {
list2.next = mergeTwoLists(list1, list2.next);
return list2;
}
}
}
- 迭代
private ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode tail = dummyHead;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
tail.next = l1;
l1 = l1.next;
} else {
tail.next = l2;
l2 = l2.next;
}
tail = tail.next;
}
tail.next = l1 == null? l2: l1;
return dummyHead.next;
}
边栏推荐
- Idea editor removes SQL statement background color SQL statement warning no data sources are configured to run this SQL And SQL dialect is not config
- Bubble sort array
- Understanding and function of polymorphism
- 职场四象限法则:时间管理四象限与职场沟通四象限「建议收藏」
- VBScript详解(一)
- AcWing 181. Turnaround game solution (search ida* search)
- [译]深入了解现代web浏览器(一)
- RPD product: super power squad nanny strategy
- RPD出品:Superpower Squad 保姆级攻略
- How to set priorities in C language? Elaborate on C language priorities
猜你喜欢
rxjs Observable 自定义 Operator 的开发技巧
Istio部署:快速上手微服务,
字典
Dictionaries
Introduction to mongodb chapter 03 basic concepts of mongodb
Introduction to program ape (XII) -- data storage
API文档工具knife4j使用详解
程序猿入门攻略(十二)——数据的存储
Shardingsphere jdbc5.1.2 about select last_ INSERT_ ID () I found that there was still a routing problem
HDL design peripheral tools to reduce errors and help you take off!
随机推荐
Start practicing calligraphy
Common problems and description of kt148a voice chip IC development
函数高阶-柯里化实现
Set up sentinel mode. Reids and redis leave the sentinel cluster from the node
pxe装机「建议收藏」
mysql函数
Automatic reading of simple books
Postman下载安装
Function high order curry realization
Zabbix5 client installation and configuration
451 implementation of memcpy, memmove and memset
AcWing 1126. 最小花费 题解(最短路—dijkstra)
Pytorch版本、CUDA版本与显卡驱动版本的对应关系
One side is volume, the other side is layoff. There are a lot of layoffs in byte commercialization department. What do you think of this wave?
为什么我对流程情有独钟?
AcWing 1129. 热浪 题解(最短路—spfa)
AcWing 343. Sorting problem solution (Floyd property realizes transitive closure)
AcWing 903. 昂贵的聘礼 题解(最短路—建图、dijkstra)
Data Lake (XII): integration of spark3.1.2 and iceberg0.12.1
Codeforces Round #802 (Div. 2) 纯补题