min-stack 1.0.0
Min Stack
Loading...
Searching...
No Matches
main.cpp
Go to the documentation of this file.
1#include <bits/stdc++.h>
2
3using namespace std;
4
6{
7private:
8 stack<int, deque<int>> s;
9 priority_queue<int, vector<int>, greater<int>> q;
10
11public:
12 MinStack() : s(), q() {}
13
14 void push(int val)
15 {
16 s.push(val);
17 q.push(val);
18 }
19
20 void pop()
21 {
22 if (s.empty() || q.empty())
23 {
24 if (s.empty())
25 throw runtime_error("min-stack.pop: empty stack");
26 else
27 throw runtime_error("min-stack.pop: empty priority queue");
28 return;
29 }
30 int el = s.top();
31 queue<int> temp;
32 while (!q.empty() && q.top() != el)
33 {
34 temp.push(q.top());
35 q.pop();
36 }
37 if (!q.empty())
38 {
39 q.pop();
40 while (!temp.empty())
41 {
42 q.push(temp.front());
43 temp.pop();
44 }
45 }
46 s.pop();
47 }
48
49 int top()
50 {
51 if (s.empty() || q.empty())
52 {
53 if (s.empty())
54 throw runtime_error("min-stack.top: empty stack");
55 else
56 throw runtime_error("min-stack.top: empty priority queue");
57 return -1;
58 }
59 return s.top();
60 }
61
62 int getMin()
63 {
64 if (s.empty() || q.empty())
65 {
66 if (s.empty())
67 throw runtime_error("min-stack.getMin: empty stack");
68 else
69 throw runtime_error("min-stack.getMin: empty priority queue");
70 }
71 return q.top();
72 }
73};
74
84int main()
85{
86 try
87 {
88 unique_ptr<MinStack> s(make_unique<MinStack>());
89 s->push(-2);
90 s->push(0);
91 s->push(-3);
92 cout << "min: " << s->getMin() << '\n';
93 s->pop();
94 cout << "top: " << s->top() << '\n';
95 cout << "min: " << s->getMin() << '\n';
96 }
97 catch(const std::exception& e)
98 {
99 cerr << e.what() << '\n';
100 }
101
102 return 0;
103}
void push(int val)
Definition main.cpp:14
priority_queue< int, vector< int >, greater< int > > q
Definition main.cpp:9
MinStack()
Definition main.cpp:12
int top()
Definition main.cpp:49
void pop()
Definition main.cpp:20
int getMin()
Definition main.cpp:62
stack< int, deque< int > > s
Definition main.cpp:8
int main()
Your MinStack object will be instantiated and called as such: MinStack* obj = new MinStack(); obj->pu...
Definition main.cpp:84