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

}

全部评论

相关推荐

鱼专:别投了,我看到有人点了第二个链接投递,还没退出界面,不合适的邮件就发过来了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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