-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23.cpp
More file actions
53 lines (52 loc) · 1.24 KB
/
23.cpp
File metadata and controls
53 lines (52 loc) · 1.24 KB
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
51
52
53
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* merge2Lists(ListNode* A, ListNode* B){
if(!A)
return B;
if(!B)
return A;
ListNode* head = new ListNode(0);
ListNode* curr = head;
while(A && B){
if(A->val <= B->val){
curr->next = A;
A = A->next;
}
else{
curr->next = B;
B = B->next;
}
curr = curr->next;
}
curr->next = (A==NULL)?B:A;
return head->next;
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
if(lists.empty())
return NULL;
int n = lists.size();
if(n==1)
return lists[0];
int i = 0;
int j = n-1;
while(i<j){
lists[i] = merge2Lists(lists[i],lists[j]);
i++;
j--;
if(i>=j){
i = 0;
}
}
return lists[0];
}
};