-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathLeetCode#22.cc
More file actions
40 lines (40 loc) · 1.09 KB
/
Copy pathLeetCode#22.cc
File metadata and controls
40 lines (40 loc) · 1.09 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
/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
ListNode* ret = NULL;
ListNode* tail = NULL;
int size = lists.size();
if(size==0) return ret;
if(size==1) return lists[0];
while(true){
int ind = -1;
for(int i=0;i<size;i++)
if(lists[i]!=NULL){
if(ind==-1 || lists[i]->val < lists[ind]->val)
ind = i;
}
if(ind==-1) break;
if(ret==NULL){
ret = tail = lists[ind];
lists[ind]=lists[ind]->next;
}
else{
tail->next = lists[ind];
tail = tail->next;
lists[ind] = lists[ind]->next;
}
}
if(tail) tail->next = NULL;
return ret;
}
};