-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path23.合并k个排序链表.cpp
More file actions
77 lines (75 loc) · 1.47 KB
/
Copy path23.合并k个排序链表.cpp
File metadata and controls
77 lines (75 loc) · 1.47 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
/*
* @lc app=leetcode.cn id=23 lang=cpp
*
* [23] 合并K个排序链表
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
// #include <queue>
// using namespace std;
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
struct cmp
{
bool operator()(ListNode *a, ListNode *b)
{
return a->val > b->val;
}
};
class Solution
{
public:
ListNode *
mergeKLists(vector<ListNode *> &lists)
{
if (lists.size() == 0)
{
return {};
}
ListNode *p_index;
ListNode *p_head;
p_index = p_head = NULL;
int first_index = 0;
priority_queue<ListNode *, vector<ListNode *>, cmp> pq;
for (int i = 0; i < lists.size(); i++)
{
if (lists[i])
{
pq.push(lists[i]);
}
}
while (!pq.empty())
{
ListNode *p_temp = pq.top();
pq.pop();
if (p_head)
{
p_index->next = p_temp;
p_index = p_temp;
}
else
{
p_index = p_head = p_temp;
}
if (p_temp->next)
{
pq.push(p_temp->next);
}
}
if (!p_head)
{
return {};
}
return p_head;
}
};