Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity
1.非递归归并
/**
* 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) {
int len = lists.size();
if(len <=0 )return NULL;
int step = 1;
ListNode *head=lists[0];
while(step < len){
int first = 0;
int second = first+step;
while(first < len){
ListNode *h1 = lists[first];
ListNode *h2 = lists[second];
head=merge(h1,h2);
lists[first] = head;
if(first!=second)
lists[second] = NULL;
first = second + step;
second = first +step;
second = second >= len ? len-1:second;
}
step *= 2;
}
return head;
}
private:
ListNode *merge(ListNode *h1,ListNode *h2){
if(h1==h2) return h1;
if(h1==NULL) return h2;
if(h2==NULL) return h1;
ListNode *pre1=NULL,*head = h1;
while(h1 && h2){
if(h1->val < h2->val) {
pre1 = h1;
h1=h1->next;
}else if(h1->val ==h2->val){
ListNode *p = h2->next;
h2->next = h1->next ;
h1->next = h2;
pre1=h1;
h1 = h2;
h2=p;
}else{
ListNode *p = h2->next;
if(pre1==NULL){
h2->next = h1;
head = h2;
pre1 = h2;
}else{
h2->next = pre1->next;
pre1->next = h2;
pre1=h2;
}
h2=p;
}
}
if(h2){
pre1->next = h2;
}
return head;
}
};
2.递归:
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
return mergeKLists(lists,0,lists.size());
}
private:
ListNode *mergeKLists(vector<ListNode *> &lists,int low,int high) {
if(low >= high || lists.size()==0) return NULL;
if(high-low==1) return lists[low];
int middle = (low+high)/2;
ListNode *h1=mergeKLists(lists,low,middle);
lists[low]=h1;
ListNode *h2=mergeKLists(lists,middle,high);
lists[middle]=h2;
ListNode *head = merge(h1,h2);
lists[low]=head;
return head;
}
ListNode *merge(ListNode *h1,ListNode *h2){
if(h1==h2) return h1;
if(h1==NULL) return h2;
if(h2==NULL) return h1;
ListNode *pre1=NULL,*head = h1;
while(h1 && h2){
if(h1->val < h2->val) {
pre1 = h1;
h1=h1->next;
}else if(h1->val ==h2->val){
ListNode *p = h2->next;
h2->next = h1->next ;
h1->next = h2;
pre1=h1;
h1 = h2;
h2=p;
}else{
ListNode *p = h2->next;
if(pre1==NULL){
h2->next = h1;
head = h2;
pre1 = h2;
}else{
h2->next = pre1->next;
pre1->next = h2;
pre1=h2;
}
h2=p;
}
}
if(h2){
pre1->next = h2;
}
return head;
}
};