-
Notifications
You must be signed in to change notification settings - Fork 0
/
Min Stack
74 lines (68 loc) · 1.17 KB
/
Min Stack
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>
// Implement class for minStack.
class minStack
{
stack<int> s;
int mini;
public:
// Constructor
minStack()
{
// Write your code here.
}
// Function to add another element equal to num at the top of stack.
void push(int num)
{
if(s.empty()){
mini = num;
s.push(num);
}
else{
if(mini <= num){
s.push(num);
}
else{
int prev = num;
num = 2*num - mini;
mini = prev;
s.push(num);
}
}
}
// Function to remove the top element of the stack.
int pop()
{
if(!s.empty()){
int data = s.top();
if(data >= mini){
s.pop();
return data;
}
else{
int prev = mini;
mini = 2*mini - data;
s.pop();
return prev;
}
}
return -1;
}
// Function to return the top element of stack if it is present. Otherwise return -1.
int top()
{
if(!s.empty()){
int data = s.top();
if(data >= mini) return data;
else return mini;
}
return -1;
}
// Function to return minimum element of stack if it is present. Otherwise return -1.
int getMin()
{
if(!s.empty()){
return mini;
}
return -1;
}
};