-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmerge k sorted lists
50 lines (45 loc) · 990 Bytes
/
merge k sorted lists
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode * res;
if(lists.size()==0) return NULL;
else if(lists.size()==1){
res=lists[0];
return res;
}
else{
ListNode * res=merge(lists[0], lists[1]);
for(int i=2; i<lists.size(); i++){
res=merge(res,lists[i]);
}
return res;
}
//return res;
}
private:
ListNode* merge(ListNode *a, ListNode *b){
if(a==NULL) return b;
if(b==NULL) return a;
ListNode *res;
if(a->val<b->val){
res=a;
res->next=merge(a->next,b);
}
else{
res=b;
res->next=merge(a,b->next);
}
return res;
}
};