当前位置:网站首页>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;
}
边栏推荐
猜你喜欢
星瑞格数据库入围“2021年度福建省信息技术应用创新典型解决方案”
Excessive dependence on subsidies, difficult collection of key customers, and how strong is the potential to reach the dream of "the first share of domestic databases"?
Dotween -- ease function
pycharm 终端部启用虚拟环境
Notification uses full resolution
平衡二叉树(AVL)
企业级日志分析系统ELK
SysOM 案例解析:消失的内存都去哪了 !| 龙蜥技术
HAVE FUN | “飞船计划”活动最新进展
What about the pointer in neural network C language
随机推荐
Laravel5.1 路由 -路由分组
Limit of total fields [1000] in index has been exceeded
Numpy -- data cleaning
Three singleton modes of unity (hungry man, lazy man, monobehavior)
The unity vector rotates at a point
企业级日志分析系统ELK
Apache Doris just "graduated": why should we pay attention to this kind of SQL data warehouse?
Plate - forme de surveillance par étapes zabbix
TCP framework___ Unity
谈谈 SAP iRPA Studio 创建的本地项目的云端部署问题
Power of leetcode-231-2
MySQL数据库基本操作-DQL-基本查询
Logback日志框架第三方jar包 免费获取
How to query the data of a certain day, a certain month, and a certain year in MySQL
A link opens the applet code. After compilation, it is easy to understand
PHP实现微信小程序人脸识别刷脸登录功能
分步式监控平台zabbix
AE learning 01: AE complete project summary
[summary of knowledge] summary of notes on using SVN in PHP
【Android -- 数据存储】使用 SQLite 存储数据