forked from sunstick/code-street
-
Notifications
You must be signed in to change notification settings - Fork 0
/
merge_k_sorted_list.cpp
39 lines (35 loc) · 984 Bytes
/
merge_k_sorted_list.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
/*
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*/
/**
* 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) {
ListNode dummy(0);
ListNode *tail = &dummy;
tail -> next = NULL;
priority_queue<pair<int, int> > pq;
for (int i = 0; i < lists.size(); i++) {
if (lists[i])
pq.push(make_pair(-lists[i] -> val, i));
}
while (!pq.empty()) {
int i = pq.top().second;
pq.pop();
tail -> next = lists[i];
lists[i] = lists[i] -> next;
tail = tail -> next;
tail -> next = NULL;
if (lists[i])
pq.push(make_pair(-lists[i] -> val, i));
}
return dummy.next;
}
};