-
-
Notifications
You must be signed in to change notification settings - Fork 156
Expand file tree
/
Copy pathMinStack.java
More file actions
40 lines (30 loc) · 791 Bytes
/
Copy pathMinStack.java
File metadata and controls
40 lines (30 loc) · 791 Bytes
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
package leetcode.medium;
import java.util.Stack;
public class MinStack {
Stack<Integer> stack;
Stack<Integer> minStack;
public MinStack() {
stack = new Stack<>();
minStack = new Stack<>();
}
public void push(int val) {
stack.push(val);
// If minStack is empty or new value is less than equal to
// the top of the minStack, push it onto the minStack
if (minStack.isEmpty() || val <= minStack.peek())
minStack.push(val);
}
public void pop() {
int poppedValue = stack.pop();
// If popped value == top of the minStack,
// pop it from the minStack as well
if (poppedValue == minStack.peek())
minStack.pop();
}
public int top() {
return stack.peek();
}
public int getMin() {
return minStack.peek();
}
}