-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge K Sorted Lists.cpp
102 lines (89 loc) · 2.15 KB
/
Merge K Sorted Lists.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
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Merge K Sorted Lists
//using priority queue
class comparator{
public:
bool operator()(ListNode* lhs, ListNode* rhs){
return lhs->val > rhs->val;
}
};
ListNode *mergeKLists(vector<ListNode *> &lists) {
int n = lists.size();
if(n == 0){
return NULL;
}
//take care of the pattern
priority_queue<ListNode*, vector<ListNode*>, comparator> pq;
vector<ListNode*>::iterator it;
for(it = lists.begin(); it != lists.end(); ){
if(*it == NULL){
lists.erase(it);
}
else{
pq.push(*it);
++it;
}
}
ListNode* head = NULL;
ListNode* tail = NULL;
while(!pq.empty()){
ListNode* curr = pq.top();
pq.pop();
if(head == NULL){
head = curr;
tail = curr;
}
else{
tail->next = curr;
tail = curr;
}
if(curr->next != NULL){
pq.push(curr->next);
}
}
if(head == NULL){
return head;
}
tail->next = NULL;
return head;
}
class comparator{
public:
bool operator()(const ListNode* lhs, const ListNode* rhs)const{
return lhs->val > rhs->val;
}
};
ListNode *mergeKLists(vector<ListNode *> &lists) {
int n = lists.size();
if(n == 0){
return NULL;
}
vector<ListNode* >::iterator it = lists.begin();
while(it != lists.end()){
if(*it == NULL){
lists.erase(it);
}
else ++it;
}
//making heap
make_heap(lists.begin(), lists.end(), comparator());
ListNode* head = NULL;
ListNode* back = NULL;
while(lists.size() > 0){
pop_heap(lists.begin(), lists.end(), comparator());
if(head == NULL){
head = lists[lists.size()-1];
lists.pop_back();
back = head;
}
else{
back->next = lists[lists.size()-1];
lists.pop_back();
back = back->next;
}
if(back->next != NULL){
lists.push_back(back->next);
push_heap(lists.begin(), lists.end(), comparator());
}
}
return head;
}