forked from kaidul/LeetCode_problems_solution
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Min_Stack.cpp
71 lines (68 loc) · 1.61 KB
/
Min_Stack.cpp
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
class MinStack {
private:
class Stack {
private:
struct Node {
int data;
Node *next;
Node(int const& data, Node *next)
: data(data)
, next(next) {
}
};
Node *head = nullptr;
int elements = 0;
public:
~Stack() {
Node *next;
for(Node* loop = head; loop != nullptr; loop = next) {
next = loop->next;
delete loop;
}
}
void push(int const& data) {
head = new Node(data, head);
++elements;
}
bool empty() const {
return head == nullptr;
}
size_t size() const {
return elements;
}
int top() const {
assert(head != nullptr);
return head->data;
}
void pop() {
assert(head != nullptr);
Node *tmp = head;
head = head->next;
--elements;
delete tmp;
}
};
// Stack stack1, stack2;
// using custom data-structure yields MLE :/
stack<int>stack1, stack2;
public:
void push(int x) {
stack2.push(x);
if(stack1.empty() or x <= stack1.top()) {
stack1.push(x);
}
}
void pop() {
int top = stack2.top();
stack2.pop();
if(top == stack1.top()) {
stack1.pop();
}
}
int top() {
return stack2.top();
}
int getMin() {
return stack1.top();
}
};