merge-two-sorted-lists
1.0.0
Merge Two Sorted Lists
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1
#include <bits/stdc++.h>
2
3
using namespace
std;
4
8
struct
ListNode
9
{
10
int
val
;
11
ListNode
*
next
;
12
ListNode
() :
val
(0),
next
(nullptr) {}
13
ListNode
(
int
x) :
val
(x),
next
(nullptr) {}
14
ListNode
(
int
x,
ListNode
*
next
) :
val
(x),
next
(
next
) {}
15
};
16
17
class
Solution
18
{
19
public
:
20
struct
Compare
21
{
22
bool
operator()
(
ListNode
* a,
ListNode
* b)
23
{
24
return
a->
val
> b->
val
;
25
}
26
};
27
28
ListNode
*
mergeTwoLists
(
ListNode
* list1,
ListNode
* list2)
29
{
30
if
(!list1 && !list2)
31
return
NULL;
32
else
if
(!list1)
33
return
list2;
34
else
if
(!list2)
35
return
list1;
36
priority_queue<ListNode*, vector<ListNode*>,
Compare
> min_heap;
37
ListNode
* current = list1;
38
while
(current != NULL)
39
{
40
min_heap.push(current);
41
current = current->
next
;
42
}
43
current = list2;
44
while
(current != NULL)
45
{
46
min_heap.push(current);
47
current = current->
next
;
48
}
49
ListNode
* head = min_heap.top();
50
min_heap.pop();
51
current = head;
52
while
(!min_heap.empty())
53
{
54
current->
next
= min_heap.top();
// dereferencing previous order
55
min_heap.pop();
56
current = current->
next
;
57
}
58
current->
next
= NULL;
59
return
head;
60
}
61
};
62
63
int
main
()
64
{
65
66
return
0;
67
}
Solution
Definition
main.cpp:18
Solution::mergeTwoLists
ListNode * mergeTwoLists(ListNode *list1, ListNode *list2)
Definition
main.cpp:28
main
int main()
Definition
main.cpp:63
ListNode
Definition for singly-linked list.
Definition
main.cpp:9
ListNode::val
int val
Definition
main.cpp:10
ListNode::ListNode
ListNode(int x)
Definition
main.cpp:13
ListNode::ListNode
ListNode()
Definition
main.cpp:12
ListNode::next
ListNode * next
Definition
main.cpp:11
ListNode::ListNode
ListNode(int x, ListNode *next)
Definition
main.cpp:14
Solution::Compare
Definition
main.cpp:21
Solution::Compare::operator()
bool operator()(ListNode *a, ListNode *b)
Definition
main.cpp:22
main.cpp
Generated by
1.9.8