-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSpecialStack.java
51 lines (48 loc) · 1.2 KB
/
SpecialStack.java
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
package Stack;
public class SpecialStack extends Stack<Integer> {
Stack<Integer> min = new Stack<>();
/* SpecialStack's member method to
insert an element to it. This method
makes sure that the min stack is
also updated with appropriate minimum
values */
void push(int x)
{
if (isEmpty() == true) {
super.push(x);
min.push(x);
}
else {
super.push(x);
int y = min.pop();
min.push(y);
if (x < y)
min.push(x);
else
min.push(y);
}
}
public Integer pop()
{
int x = super.pop();
min.pop();
return x;
}
/* SpecialStack's member method to get
minimum element from it. */
int getMin()
{
int x = min.pop();
min.push(x);
return x;
}
public static void main(String[] args) {
SpecialStack s = new SpecialStack();
s.push(10);
s.push(20);
s.push(30);
System.out.println(s.getMin());
s.push(5);
System.out.println(s.getMin());
}
}