forked from ppsirker/dsalgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStackMinimum.java
53 lines (44 loc) · 869 Bytes
/
StackMinimum.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
52
53
/*
For problem and solution description please visit the link below
http://www.dsalgo.com/2013/02/StackMinimum.php.html
*/
package com.dsalgo;
import java.util.Stack;
public class StackMinimum
{
private Stack<Integer> stack = new Stack<Integer>();
private Stack<Integer> minStack = new Stack<Integer>();
public Integer push(Integer item)
{
if(stack.empty())
{
stack.push(item);
minStack.push(item);
return item;
}
Integer currentMin=minStack.peek();
if(currentMin < item)
minStack.push(currentMin);
else
minStack.push(item);
stack.push(item);
return item;
}
public Integer pop()
{
if(stack.size()==0)
return null;
minStack.pop();
return stack.pop();
}
public Integer getMinimum()
{
if(minStack.empty())
return null;
return minStack.peek();
}
public int size()
{
return stack.size();
}
}