-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMerge_K_sorted_lists.cpp
More file actions
57 lines (50 loc) · 1.18 KB
/
Merge_K_sorted_lists.cpp
File metadata and controls
57 lines (50 loc) · 1.18 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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
public:
ListNode* mergeKLists(vector<ListNode*>& lists)
{
int size = lists.size();
ListNode *head = NULL;
vector<int> numbers;
for(auto curList : lists)
{
while(curList != NULL)
{
numbers.push_back(curList->val);
curList = curList->next;
}
}
sort(numbers.begin(),numbers.end());
head = AddNumbers(numbers);
return head;
}
ListNode* AddNumbers(vector<int> numbers)
{
if(numbers.size() == NULL)
return NULL;
ListNode *head = NULL;
ListNode *tmp;
for(auto it : numbers)
{
if(head == NULL)
{
head = new ListNode(it);
tmp = head;
}
else
{
tmp->next = new ListNode(it);
tmp = tmp->next;
}
}
return head;
}
};