-
Notifications
You must be signed in to change notification settings - Fork 9
/
Merge.CPP
43 lines (40 loc) · 1.01 KB
/
Merge.CPP
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
ListNode * sortLists(ListNode * l1, ListNode* l2){
if(!l1) return l2;
if(!l2) return l1;
ListNode * l = nullptr;
ListNode * ret = nullptr;
if(l2->val <= l1->val){
l = l2;
l2 = l2->next;
}else{
l = l1;
l1 = l1->next;
}
ret = l;
while(l1 && l2){
if(l2->val <= l1->val){
l->next = l2;
l2 = l2->next;
}else{
l->next = l1;
l1 = l1->next;
}
l = l->next;
}
if(l1 || l2){
if(l1){
l->next = l1;
}else{
l->next= l2;
}
}
return ret;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode * ret = nullptr;
for(int i = 0; i < lists.size(); ++i){
ListNode * temp = lists[i];
ret = sortLists(ret,temp);
}
return ret;
}