-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgetMinStack.cpp
More file actions
74 lines (68 loc) · 1.47 KB
/
getMinStack.cpp
File metadata and controls
74 lines (68 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
#include <bits/stdc++.h>
#include <climits>
#include <list>
using namespace std;
class MyStack{
public:
MyStack(){
num_head = new _Node_;
min_head = new _Node_;
min_head->v = INT_MAX;
num_head->root = true;
min_head->root = true;
}
void push(int num){
_Node_* temp = new _Node_;
temp->next = num_head;
temp->v = num;
num_head = temp;
if (num <= min_head->v){
_Node_* temp1 = new _Node_;
temp1->next = min_head;
temp1->v = num;
min_head = temp1;
}
}
void pop(){
if (num_head->root)
return;
int v = num_head->v;
_Node_* temp = num_head->next;
delete num_head;
num_head = temp;
if (v <= min_head->v){
temp = min_head->next;
delete min_head;
min_head = temp;
}
}
int getMin(){
return min_head->v;
}
private:
struct _Node_{
_Node_* next = nullptr;
int v = 0;
bool root = false;
};
_Node_* num_head, * min_head;
};
int main(){
int n;
cin >> n;
string s;
MyStack stack;
while (n--){
cin >> s;
if (s == "push"){
int num;
cin >> num;
stack.push(num);
}else if (s == "pop"){
stack.pop();
}else if (s == "getMin"){
cout << stack.getMin() << endl;
}
}
return 0;
}