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
3using namespace std;
4
8struct ListNode
9{
10 int val;
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
18{
19public:
20 struct Compare
21 {
23 {
24 return a->val > b->val;
25 }
26 };
27
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
63int main()
64{
65
66 return 0;
67}
ListNode * mergeTwoLists(ListNode *list1, ListNode *list2)
Definition main.cpp:28
int main()
Definition main.cpp:63
Definition for singly-linked list.
Definition main.cpp:9
int val
Definition main.cpp:10
ListNode(int x)
Definition main.cpp:13
ListNode()
Definition main.cpp:12
ListNode * next
Definition main.cpp:11
ListNode(int x, ListNode *next)
Definition main.cpp:14
bool operator()(ListNode *a, ListNode *b)
Definition main.cpp:22