码迷,mamicode.com
首页 > 编程语言 > 详细

合并K个排序链表

时间:2019-10-12 23:06:01      阅读:105      评论:0      收藏:0      [点我收藏+]

标签:als   ptr   vat   null   turn   ini   链表   lists   ati   

合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。

示例:

输入:
[
  1->4->5,
  1->3->4,
  2->6
]
输出: 1->1->2->3->4->4->5->6

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if(lists.empty())
            return nullptr;
        
        for(int i=1;i<lists.size();++i)
            mergeLists(lists[0],lists[i]);
        
        return lists[0];
    }
private:
    ListNode* mergeLists(ListNode* &l1,ListNode *l2)
    {
        if(!l1&&!l2)
            return nullptr;
        else if(!l1||!l2)
            return l1?l1:l1=l2;
       
        ListNode* head=new ListNode(-1);
        ListNode* H=head;
        while(l1&&l2)
        {
            if(l1->val<=l2->val)
            {
                H->next=l1;
                H=H->next;
                l1=l1->next;
            }
            else
            {
                H->next=l2;
                H=H->next;
                l2=l2->next;
            }
        }
        H->next=l1?l1:l2;
        l1=head->next;
        head->next=nullptr;
        delete head;
        return l1;
    }
};

 堆排序

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if(lists.empty())
            return nullptr;
        
        ListNode head(-1);
        ListNode *H=&head;
        make_heap(lists.begin(),lists.end(),cmpNode);
        while(!lists.empty()&&lists.front())
        {
            pop_heap(lists.begin(),lists.end(),cmpNode);
            H->next=lists.back();
            H=H->next;
            lists.back()=lists.back()->next;
            if(!lists.back())
                lists.pop_back();
            else
                make_heap(lists.begin(),lists.end(),cmpNode);
        }
        return head.next;
    }
    static bool cmpNode(ListNode *l1,ListNode *l2)
    {
        if(!l1||!l2)
            return !l1?true:false;
        
        return l1->val>=l2->val;
    }
};

 

合并K个排序链表

标签:als   ptr   vat   null   turn   ini   链表   lists   ati   

原文地址:https://www.cnblogs.com/tianzeng/p/11664112.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!