-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSpecialstack.cpp
More file actions
95 lines (86 loc) · 1.95 KB
/
Specialstack.cpp
File metadata and controls
95 lines (86 loc) · 1.95 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include<stack>
#include<limits.h>
class SpecialStack {
stack<int>s;
int mini=INT_MAX; //to calculate min everytime
// Define the data members.
/*----------------- Public Functions of SpecialStack -----------------*/
public:
void push(int data) {
// Implement the push() function.
//check if empty
if(s.empty())
{
//simply push data to stack
s.push(data);
mini=data; //update mini
}
else
{
//not empty
if(data<mini)
{
//data smaller than mini
s.push(2*data-mini);
//upadte mini
mini=data;
}
else
{
//data is bigger
s.push(data);
}
}
}
int pop() {
// Implement the pop() function.
//check if stack is empty
if(s.empty())
{
return -1;
}
int curr=s.top(); //curr is stack ka top
s.pop();
if(curr>mini)
{
//curr is bigger than mini
//normal pop
return curr;
}
else
{
//if curr is smaller than mini
int prevmini=mini;
int val=2*mini-curr;
mini=val; //update mini
return prevmini;
}
}
int top() {
// Implement the top() function.
if(s.empty())
{
return -1;
}
int curr=s.top();
if(curr<mini)
{
return mini;
}
else
{
//curr is bigger
return curr;
}
}
bool isEmpty() {
// Implement the isEmpty() function.
return s.empty();
}
int getMin() {
// Implement the getMin() function.
if(s.empty())
return -1;
return mini;
}
};