您的位置:首页 > 其它

leetcode-Merge k Sorted Lists-23(未完待续)

2016-06-09 17:05 295 查看
合并k个有序链表

每次合并相邻两个就行,直接用一趟归并排序的函数,时间k*max(length),空间ON,因为在一趟归并排序时要用一个单独的链表存储结果

网上说得最多的是用堆来做,以后完善

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* merge(ListNode* l1,ListNode* l2){
if(l1==NULL) return l2;
if(l2==NULL) return l1;
ListNode* head=NULL;
ListNode* tail=NULL;
ListNode* p=l1;
ListNode* q=l2;
if(p->val <= q->val){
head=p;
tail=p;
p=p->next;
tail->next=NULL;
}
else{
head=q;
tail=q;
q=q->next;
tail->next=NULL;
}
while(p&&q){
if(p->val <= q->val){
tail->next=p;
tail=p;
p=p->next;
tail->next=NULL;
}
else{
tail->next=q;
tail=q;
q=q->next;
tail->next=NULL;
}
}
if(p) tail->next=p;
else tail->next=q;
return head;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.size()==0) return NULL;
ListNode* head=lists[0];
for(int i=1;i<lists.size();i++){
head=merge(head,lists[i]);
}
return head;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode