-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy pathmerge_k_sorted_list.c
46 lines (41 loc) · 989 Bytes
/
merge_k_sorted_list.c
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
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct cmp {
bool operator() (const ListNode *a, const ListNode *b)
{
if (a->val < b->val)
return false;
else
return true;
}
};
ListNode *mergeKLists(vector<ListNode *> &lists) {
priority_queue<ListNode *, vector<ListNode *>, cmp> heap;
for (int i = 0; i < lists.size(); i++) {
if (lists[i]) {
// for the corner case: [{}]
heap.push(lists[i]);
}
}
ListNode *prevNode = NULL;
ListNode *head = NULL;
ListNode *curNode = NULL;
while (!heap.empty()) {
curNode = heap.top();
heap.pop();
if (head == NULL) {
head = curNode;
}
if (curNode->next) {
heap.push(curNode->next);
}
if (prevNode) {
prevNode->next = curNode;
}
prevNode = curNode;
}
return head;
}