forked from fanfank/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmerge-k-sorted-lists.cpp
More file actions
31 lines (31 loc) · 899 Bytes
/
merge-k-sorted-lists.cpp
File metadata and controls
31 lines (31 loc) · 899 Bytes
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
/**
* 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) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(lists.size() == 0)
return NULL;
ListNode *head = NULL, **pHead = &head;
while(true) {
ListNode **tmp = &lists[0];
for(int i = 1; i < lists.size(); ++i) {
if(*tmp == NULL || (lists[i] != NULL && (*tmp)->val > lists[i]->val)) {
tmp = &lists[i];
}
}
if(NULL == *tmp)
break;
*pHead = *tmp;
*tmp = (*tmp)->next;
pHead = &((*pHead)->next);
}
return head;
}
};