forked from daiwb/Algorithm
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmergeKLists.cpp
More file actions
77 lines (68 loc) · 1.76 KB
/
mergeKLists.cpp
File metadata and controls
77 lines (68 loc) · 1.76 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <climits>
#include <algorithm>
#include <string>
#include <cstring>
#include <vector>
#include <queue>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);++i)
#define FOR(i,a,b) for(int i=(a);i<=(b);++i)
#define RFOR(i,a,b) for(int i=(a);i>=(b);--i)
typedef long long LL;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
if (lists.size() == 0) return NULL;
int k = lists.size();
priority_queue<pair<int, int> > que;
REP(i,k) {
if (lists[i] != NULL) {
que.push(make_pair(-lists[i]->val, i));
}
}
ListNode* cur = NULL;
ListNode* root = NULL;
while (!que.empty()) {
int idx = que.top().second;
que.pop();
if (cur == NULL) {
cur = lists[idx];
root = lists[idx];
} else {
cur->next = lists[idx];
cur = cur->next;
}
lists[idx] = lists[idx]->next;
if (lists[idx] != NULL) {
que.push(make_pair(-lists[idx]->val, idx));
}
}
return root;
}
};
int main() {
ListNode n1 = ListNode(1);
ListNode n2 = ListNode(4);
n1.next = &n2;
ListNode n3 = ListNode(5);
n2.next = &n3;
ListNode n4 = ListNode(2);
ListNode n5 = ListNode(3);
n4.next = &n5;
vector<ListNode *> lists;
lists.push_back(&n1);
lists.push_back(&n4);
Solution s = Solution();
ListNode* cur = s.mergeKLists(lists);
while (cur != NULL) {
cout << cur->val << endl;
cur = cur->next;
}
return 0;
}