当前位置:网站首页>链表-合并两个排序的列表
链表-合并两个排序的列表
2022-07-26 17:33:00 【早田凛凛子】
题目:
输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。
要求:空间复杂度 O(1)O(1),时间复杂度 O(n)O(n)
如输入{1,3,5},{2,4,6}时,合并后的链表为{1,2,3,4,5,6},所以对应的输出为{1,2,3,4,5,6},转换过程如下图所示:
解题思路:
题目中有很重要的一个信息是:两个链表都是递增的。
说明最终合成的列表的第一个结点,一定是两个链表的头结点中较小的那个。而结果链表接下来的结点,应该是两个链表接下来的结点中较小的结点。
根据这些信息我们便可以编写代码了。
函数:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
ListNode* list=new ListNode(0);//初始化一个val为0,next为null的结点,作为结果链表的头结点。
ListNode* cur=list;//cur需要随着过程的进行而变化。list不会,最终返回list->next,最终链表。
while(pHead1 && pHead2){
if(pHead1->val<pHead2->val){
cur->next=pHead1;
pHead1=pHead1->next;
}else{
cur->next=pHead2;
pHead2=pHead2->next;
}
cur=cur->next;
}
//将两个链表中剩余的部分连接到结果链表中
cur->next=pHead1?pHead1:pHead2;
return list->next;
}
};
边栏推荐
- SQL determines whether a column contains Chinese characters, English characters, pure numbers, and data interception
- 5、 Parameter server principle, code implementation
- [day3] reconstruction of roads
- 相对路径与绝对路径
- It is said that the salary of Alibaba P7 is really fragrant
- 2022 Henan Mengxin League game (3): Henan University
- openssl
- 十年架构五年生活-06 离职的冲动
- .Net CLR GC 动态加载短暂堆阈值的计算及阈值超量的计算
- LeetCode50天刷题计划(Day 5—— 最长回文子串 10.50-13:00)
猜你喜欢

Week 17 free intrusion pointer exercise - output maximum

百度飞桨EasyDL X 韦士肯:看轴承质检如何装上“AI之眼”

Click hijacking attack
![[training Day2] sculpture](/img/d9/2e2ee8b4d995a29204afba889da635.png)
[training Day2] sculpture

隐私计算基础组件系列-混淆电路
![[unity3d] rocker](/img/b7/40643a2676b251c185ce58840f7581.png)
[unity3d] rocker

AI zhetianchuan ml unsupervised learning

ssm练习第四天_获取用户名_用户退出_用户crud_密码加密_角色_权限

2、 Topic communication principle, code implementation

Machine learning by Li Hongyi 2. Regression
随机推荐
剑指offer 跳台阶扩展问题
LeetCode50天刷题计划(Day 3—— 串联所有单词的子串 10.00-13.20)
BulletGraph(子弹图、项目符号图)
链表-倒数最后k个结点
Leetcode 0137. number II that appears only once
Drools basic grammar
During the oppo interview, 16 questions were thrown over. I was stupid
Bulletgraph (bullet diagram, bullet diagram)
菜鸟 CPaaS 平台微服务治理实践
贪心——455. 分发饼干
效率提升98%!高海拔光伏电站运维巡检背后的AI利器
Is it safe for Changzheng securities to open an account?
数据仓库:详解维度建模之事实表
The Agile Manifesto has four values and twelve principles
Three ways of de duplication in SQL
隐私计算基础组件系列-混淆电路
ssm练习第四天_获取用户名_用户退出_用户crud_密码加密_角色_权限
.Net CLR GC 动态加载短暂堆阈值的计算及阈值超量的计算
Continue to work hard on your skills, and the more you learn, the more you will learn
Leetcode 50 day question brushing plan (day 2 - the longest substring without repeated characters 10.00-12.00)