Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
借用了之前的两个已排序链表合并的代码,再依次遍历所有链表,进行两两合并,方法有点弱智,下篇转载一下别人的想法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
if(!l1 && !l2) return NULL;
if(l1 && !l2) return l1;
if(!l1 && l2) return l2;
struct ListNode* p1=l1;
struct ListNode* p2=l2;
struct ListNode* ret_head=NULL;
struct ListNode* ret_p=NULL;
if(p1->val > p2->val){
ret_head=p2;
p2=p2->next;
} else {
ret_head=p1;
p1=p1->next;
}
ret_head->next=NULL;
ret_p=ret_head;
while(p1 && p2){
if(p1->val > p2->val){
ret_p->next=p2;
p2=p2->next;
} else {
ret_p->next=p1;
p1=p1->next;
}
ret_p=ret_p->next;
}
if(p1){
ret_p->next=p1;
}
if(p2){
ret_p->next=p2;
}
return ret_head;
}
struct ListNode* mergeKLists(struct ListNode** lists, int listsSize) {
if(listsSize == 0)return NULL;
struct ListNode* res = lists[0];
for(int i = 1; i < listsSize ; i++)
res = mergeTwoLists(res, lists[i]);
return res;
}