Skip to content

Commit cc1bac4

Browse files
authored
23. Merge k Sorted Lists
1 parent 97b594e commit cc1bac4

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

mergeKLists.cpp

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode() : val(0), next(nullptr) {}
7+
* ListNode(int x) : val(x), next(nullptr) {}
8+
* ListNode(int x, ListNode *next) : val(x), next(next) {}
9+
* };
10+
*/
11+
class Solution {
12+
public:
13+
ListNode* mergeKLists(vector<ListNode*>& lists) {
14+
map<int, int> freq;
15+
for(int i = 0 ; i < lists.size(); ++i) {
16+
auto node = lists[i]; // take the head
17+
while(node) {
18+
// take the node's val
19+
int temp = node ->val;
20+
// put it in the ordered map
21+
freq[temp]++;
22+
node = node->next;
23+
}
24+
}
25+
ListNode dummy(0); // create new linked list
26+
ListNode* tail = &dummy;
27+
for(auto i : freq) {
28+
while(i.second!=0) {
29+
// create a node for every item
30+
ListNode* newnode = new ListNode(i.first);
31+
// add it to tail
32+
tail->next = newnode;
33+
tail = tail->next;
34+
// decrement the freq
35+
i.second--;
36+
}
37+
}
38+
return dummy.next;
39+
}
40+
};

0 commit comments

Comments
 (0)