-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGetMinStack.java
More file actions
53 lines (47 loc) · 1.57 KB
/
GetMinStack.java
File metadata and controls
53 lines (47 loc) · 1.57 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
import java.util.Stack;
public class GetMinStack {
private Stack<Integer> stackData;
private Stack<Integer> stackMin;
public GetMinStack() {
this.stackData = new Stack<Integer>();
this.stackMin = new Stack<Integer>();
}
public void push(int obj) {
this.stackData.push(obj);
if (this.stackMin.isEmpty()) {
this.stackMin.push(obj);
} else {
int minnum = Math.min(obj, this.stackMin.peek());
this.stackMin.push(minnum);
}
}
public Integer pop() {
if (this.stackData.isEmpty()) {
throw new RuntimeException("Your Stack is empty!");
}
int value = this.stackData.pop();
this.stackMin.pop();
return value;
}
public Integer getMin() {
if (this.stackMin.isEmpty()) {
throw new RuntimeException("Your stack is empty!");
}
return this.stackMin.peek();
}
public static void main(String[] args) {
GetMinStack mystack = new GetMinStack();
mystack.push(6);
System.out.println("Min: " + mystack.getMin());
mystack.push(7);
System.out.println("Min: " + mystack.getMin());
mystack.push(4);
System.out.println("Min: " + mystack.getMin());
mystack.push(2);
System.out.println("Min: " + mystack.getMin());
System.out.println("pop: " + mystack.pop());
System.out.println("Min: " + mystack.getMin());
System.out.println("pop: " + mystack.pop());
System.out.println("Min: " + mystack.getMin());
}
}