forked from yuzhangcmu/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMinStack.java
More file actions
executable file
·51 lines (41 loc) · 1.12 KB
/
Copy pathMinStack.java
File metadata and controls
executable file
·51 lines (41 loc) · 1.12 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
package Algorithms.stack;
import java.util.Stack;
class MinStack {
public static void main(String[] strs) {
MinStack sta = new MinStack();
//push(512),push(-1024),push(-1024),push(512),pop,getminStack,pop,getminStack,pop,getminStack
sta.push(512);
sta.push(-1024);
sta.push(-1024);
sta.push(512);
sta.pop();
sta.getminStack();
sta.pop();
sta.getminStack();
sta.pop();
sta.getminStack();
}
Stack<Integer> elements = new Stack<Integer>();
Stack<Integer> minStack = new Stack<Integer>();
public void push(int x) {
elements.push(x);
if (minStack.isEmpty() || x <= minStack.peek()) {
minStack.push(x);
}
}
public void pop() {
if (elements.isEmpty()) {
return;
}
if (elements.peek().equals(minStack.peek())) {
minStack.pop();
}
elements.pop();
}
public int top() {
return elements.peek();
}
public int getminStack() {
return minStack.peek();
}
}