题解 | #合并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;

}

全部评论

相关推荐

04-27 15:01
早稲田大学 Java
牛客72191338...:可能是时间点的问题,四月底机会确实会相对少点,但佬这个学历摆在这,会有机会的
简历中的项目经历要怎么写
点赞 评论 收藏
分享
04-15 14:28
已编辑
Java
程序员小白条:学院+两段经典项目+技术栈,最大众的简历,纯看运气
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务