当前位置:网站首页>23. 合并K个升序链表-c语言
23. 合并K个升序链表-c语言
2022-07-07 14:15:00 【Mr Gao】
23. 合并K个升序链表-c语言
给你一个链表数组,每个链表都已经按升序排列。
请你将所有链表合并到一个升序链表中,返回合并后的链表。
示例 1:
输入:lists = [[1,4,5],[1,3,4],[2,6]]
输出:[1,1,2,3,4,4,5,6]
解释:链表数组如下:
[
1->4->5,
1->3->4,
2->6
]
将它们合并到一个有序链表中得到。
1->1->2->3->4->4->5->6
示例 2:
输入:lists = []
输出:[]
示例 3:
输入:lists = [[]]
输出:[]
解题代码如下,很不错的题目:
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */
struct ListNode* merge(struct ListNode* list1,struct ListNode* list2){
struct ListNode*p=(struct ListNode*)malloc(sizeof(struct ListNode));
p->next=NULL;
struct ListNode *s=p;
if(list1==NULL&&list2){
p->next=list2;
}
if(list2==NULL&&list1){
p->next=list1;
}
while(list1&&list2){
if(list1->val<list2->val){
p->next=list1;
p=p->next;
list1=list1->next;
if(list1==NULL){
p->next=list2;
}
}
else{
p->next=list2;
p=p->next;
list2=list2->next;
if(list2==NULL){
p->next=list1;
}
}
}
return s->next;;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize){
int i;
if(listsSize==0){
return NULL;
}
struct ListNode *l=lists[0];
for(i=1;i<listsSize;i++){
l=merge(l,lists[i]);
}
return l;
}
边栏推荐
猜你喜欢
Tragedy caused by deleting the console statement
Application example of infinite list [uigridview]
Apache Doris刚“毕业”:为什么应关注这种SQL数据仓库?
深度之眼(六)——矩阵的逆(附:logistic模型一些想法)
Apache Doris just "graduated": why should we pay attention to this kind of SQL data warehouse?
You Yuxi, coming!
Vs tool word highlight with margin
统计学习方法——感知机
Logback logging framework third-party jar package is available for free
星瑞格数据库入围“2021年度福建省信息技术应用创新典型解决方案”
随机推荐
TCP framework___ Unity
How does laravel run composer dump autoload without emptying the classmap mapping relationship?
IP地址和物理地址有什么区别
安科瑞电网智能化发展的必然趋势电力系统采用微机保护装置是
Logback日志框架第三方jar包 免费获取
121. 买卖股票的最佳时机
The differences between exit, exit (0), exit (1), exit ('0 '), exit ('1'), die and return in PHP
Numpy --- basic learning notes
asyncio 概念和用法
SysOM 案例解析:消失的内存都去哪了 !| 龙蜥技术
Strengthen real-time data management, and the British software helps the security construction of the medical insurance platform
如何在shell中实现 backspace
Shader_ Animation sequence frame
用手机在通达信上开户靠谱吗?这样炒股有没有什么安全隐患
【C 语言】 题集 of Ⅹ
iptables只允许指定ip地址访问指定端口
喜讯!科蓝SUNDB数据库与鸿数科技隐私数据保护管理软件完成兼容性适配
Unity的三种单例模式(饿汉,懒汉,MonoBehaviour)
ThinkPHP URL 路由简介
PyTorch 中的乘法:mul()、multiply()、matmul()、mm()、mv()、dot()