-
Notifications
You must be signed in to change notification settings - Fork 14
/
MinStack.java
56 lines (44 loc) · 959 Bytes
/
MinStack.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
54
55
56
package com.demo;
import java.util.Stack;
public class MinStack {
private Stack<Integer> stack = new Stack<Integer>();
private Stack<Integer> minStack = new Stack<Integer>();
public static void main(String[] args) {
MinStack m = new MinStack();
m.push(4);
m.push(8);
m.push(1);
System.out.println(m.getMin());
m.pop();
System.out.println(m.getMin());
m.pop();
System.out.println(m.getMin());
m.pop();
System.out.println(m.getMin());
}
public void push(Integer newVal) {
if (minStack.isEmpty()) {
minStack.push(newVal);
} else {
if (newVal < minStack.peek()) {
minStack.push(newVal);
}
}
stack.push(newVal);
}
public Integer pop() {
if (stack.isEmpty()) {
return null;
}
Integer result = stack.pop();
if (!minStack.isEmpty()) {
if (result.equals(minStack.peek())) {
minStack.pop();
}
}
return result;
}
public Integer getMin() {
return minStack.peek();
}
}