题解 | #合并k个已排序的链表#

合并k个已排序的链表

https://www.nowcoder.com/practice/65cfde9e5b9b4cf2b6bafa5f3ef33fa6

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 *	ListNode(int x) : val(x), next(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param lists ListNode类vector 
     * @return ListNode类
     */
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        // write code here
        if(lists.empty()){return nullptr;}
        if(lists.size()==1){return lists[0];}
	  //分治法,每次只合并前两个链表
        for(int i=0;i<=lists.size()-2;i++){
		  //合并当前两个链表,并准备好与下一轮的链表合并
            lists[i+1]=sortList(lists[i], lists[i+1]);
        }
        return lists[lists.size()-1];
    }
  //合并排序两个链表
    ListNode* sortList(ListNode* phead1,ListNode* phead2){
       if(phead1==nullptr){return phead2;}
       if(phead2==nullptr){return phead1;}
        ListNode* newhead1=new ListNode(0);
        ListNode* cur=newhead1;
        while(phead1!=nullptr && phead2!=nullptr){
            if(phead1->val<=phead2->val){
                cur->next=phead1;
                phead1=phead1->next;
                cur=cur->next;
            }
            else if(phead1->val>phead2->val){
                cur->next=phead2;
                phead2=phead2->next;
                cur=cur->next;
            }
        }
        if(phead1!=nullptr){cur->next=phead1;}
        if(phead2!=nullptr){cur->next=phead2;}
        ListNode* newhead=newhead1->next;
        free(newhead1);
        return newhead;
    }
};

全部评论

相关推荐

点赞 评论 收藏
分享
04-18 00:32
已编辑
中南大学 Java
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务