-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMin_Stack.cpp
39 lines (34 loc) · 953 Bytes
/
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
#include <bits/stdc++.h>
// Implement class for minStack.
class minStack
{
stack<pair<int, int>> s;
public:
// Constructor
minStack() {}
// Function to add another element equal to num at the top of stack.
void push(int num)
{
if (s.empty())
s.push({num, num});
else if (s.top().second < num)
s.push({num, s.top().second});
else
s.push({num, num});
}
// Function to remove the top element of the stack.
int pop()
{
if (s.empty())
return -1;
auto t = s.top();
s.pop();
return t.first;
}
// Function to return the top element of stack if it is present. Otherwise
// return -1.
int top() { return s.empty() ? -1 : s.top().first; }
// Function to return minimum element of stack if it is present. Otherwise
// return -1.
int getMin() { return s.empty() ? -1 : s.top().second; }
};