-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmergeKLists.cpp
40 lines (40 loc) · 1.17 KB
/
mergeKLists.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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
map<int, int> freq;
for(int i = 0 ; i < lists.size(); ++i) {
auto node = lists[i]; // take the head
while(node) {
// take the node's val
int temp = node ->val;
// put it in the ordered map
freq[temp]++;
node = node->next;
}
}
ListNode dummy(0); // create new linked list
ListNode* tail = &dummy;
for(auto i : freq) {
while(i.second!=0) {
// create a node for every item
ListNode* newnode = new ListNode(i.first);
// add it to tail
tail->next = newnode;
tail = tail->next;
// decrement the freq
i.second--;
}
}
return dummy.next;
}
};