题解 | #合并k个已排序的链表#
合并k个已排序的链表
https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param lists ListNode类一维数组
* @param listsLen int lists数组长度
* @return ListNode类
*/
#include <math.h>
#include <stdlib.h>
struct ListNode* mergeKLists(struct ListNode** lists, int listsLen ) {
// write code here
if (listsLen==0) {
return NULL;
}
int i;
if(listsLen==1){return lists[0];}
struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *cur,*newH;
head->next=lists[0];
for(i=1;i<listsLen;i++)//循环两两合并
{
newH = head->next;
cur=head;
while(newH!=NULL&&lists[i]!=NULL)
{
if(newH->val<=lists[i]->val)
{
cur->next = newH;
newH=newH->next;
cur=cur->next;
}else{
cur->next = lists[i];
lists[i]=lists[i]->next;
cur=cur->next;
}
}
if(newH==NULL){
cur->next=lists[i];
}
if (lists[i]==NULL) {
cur->next=newH;
}
}
return head->next;
}


查看8道真题和解析