-
Notifications
You must be signed in to change notification settings - Fork 42
/
extraspace.cpp
99 lines (73 loc) · 1.68 KB
/
extraspace.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <bits/stdc++.h>
using namespace std;
struct MyStack {
stack<int> s;
int minEle;
void getMin()
{
if (s.empty())
cout << "Stack is empty\n";
else
cout << "Minimum Element in the stack is: "
<< minEle << "\n";
}
void peek()
{
if (s.empty()) {
cout << "Stack is empty ";
return;
}
int t = s.top(); // Top element.
cout << "Top Most Element is: ";
(t < minEle) ? cout << minEle : cout << t;
}
void pop()
{
if (s.empty()) {
cout << "Stack is empty\n";
return;
}
cout << "Top Most Element Removed: ";
int t = s.top();
s.pop();
if (t < minEle) {
cout << minEle << "\n";
minEle = 2 * minEle - t;
}
else
cout << t << "\n";
}
void push(int x)
{
if (s.empty()) {
minEle = x;
s.push(x);
cout << "Number Inserted: " << x << "\n";
return;
}
// If new number is less than minEle
else if (x < minEle) {
s.push(2 * x - minEle);
minEle = x;
}
else
s.push(x);
cout << "Number Inserted: " << x << "\n";
}
};
// Driver Code
int main()
{
MyStack s;
s.push(3);
s.push(5);
s.getMin();
s.push(2);
s.push(1);
s.getMin();
s.pop();
s.getMin();
s.pop();
s.peek();
return 0;
}