当前位置:网站首页>剑指 Offer 25. 合并两个排序的链表
剑指 Offer 25. 合并两个排序的链表
2022-07-27 17:22:00 【[email protected]】

https://leetcode.cn/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof/
思路一:迭代
同时遍历两个链表,比较两个链表当前的元素,将较小的元素添加到新的链表中,同时移动较小元素所在链表的指针;最后如果哪个链表不为空,直接将该链表上面剩余的元素全部连接到新的链表上面
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode dummy=new ListNode();
ListNode cur=dummy;
while(l1!=null&&l2!=null){
if(l1.val<l2.val){
cur.next=l1;
l1=l1.next;
}else{
cur.next=l2;
l2=l2.next;
}
cur=cur.next;
}
if(l1!=null){
cur.next=l1;
}
if(l2!=null){
cur.next=l2;
}
return dummy.next;
}
}
//O(n)
//O(1)
思路二:递归
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null){
return l2;
}
if(l2==null){
return l1;
}
if(l1.val<l2.val){
l1.next=mergeTwoLists(l1.next,l2);
return l1;
}else{
l2.next=mergeTwoLists(l1,l2.next);
return l2;
}
}
}
//O(n)
//O(n)
版权声明
本文为[[email protected]]所创,转载请带上原文链接,感谢
https://blog.csdn.net/qq_43478694/article/details/126006709
边栏推荐
- AcWing 692. G巴士计数 差分+前缀和
- VS2017#include 'xxx.h'
- Release Samsung 3J1 sensor: the code implies that the safety of pixel 7 face recognition will be greatly increased
- Hacker introductory tutorial (very detailed) from zero basic introduction to proficiency, it is enough to read this one.
- 注入攻击
- Detailed explanation of the underlying data structure of redis
- Common operators 9.21
- Virtualbox:ssh connection
- ECU的软硬件架构
- ToggleButton(按钮开关)
猜你喜欢

VS2017#include 'xxx.h'

Cesium常用坐标系详细介绍

全局函数

Detailed interpretation of IEC104 protocol (I) protocol structure

Session攻击

SystemService(系统服务)

Systemservice (system service)

Binary search tree

No experts! Growth secrets for junior and intermediate programmers and "quasi programmers" who are still practicing in Universities

顶级“黑客”能厉害到什么地步?无信号也能上网,专家:高端操作!
随机推荐
Unity-FairyGUI播放视频(Lua)
Arrayadapter (array adapter) and simpleadapter (simple adapter)
[basic knowledge of deep learning - 44] the method of realizing multiple classification by logistic regression
pytorch lstm+attention
Online Judge 输出超限
Sharepreference (storage)
C#网络应用编程,实验一:WPF练习
What's new in helix QAC 2022.2, the ace code static testing tool (1)
四大组件之ContentProvider
SharePreference(存储)
[basic knowledge of deep learning - 45] distance calculation methods commonly used in machine learning
Marqueetextview (running lantern)
C243:考试排名
[basic knowledge of deep learning - 49] kmeans
TSMC 5nm is about to mass produce: Apple A14 monopolizes 70% of the production capacity, and Huawei Kirin 1020 takes 30%
The go zero singleton service uses generics to simplify the registration of handler routes
View pagoda PHP extension directory
SystemService(系统服务)
GestureOverlayView(手势识别2)
能上QQ但网页打不开