Skip to content

Commit 3001311

Browse files
committed
Solution for: min stack
1 parent 534c690 commit 3001311

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

src/leetcode/MinStack.java

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
package leetcode;
2+
3+
import java.util.Stack;
4+
5+
public class MinStack {
6+
private Stack<Integer> stack = new Stack<>();
7+
private int min= Integer.MAX_VALUE;
8+
9+
public static void main(String[] args){
10+
MinStack obj = new MinStack();
11+
obj.push(-2);
12+
obj.push(0);
13+
obj.push(-3);
14+
System.out.println(obj.getMin()); //-3
15+
obj.pop();
16+
System.out.println(obj.top()); //0
17+
System.out.println(obj.getMin()); //-2
18+
}
19+
20+
/** initialize your data structure here. */
21+
public MinStack() {
22+
23+
}
24+
25+
public void push(int x) {
26+
if(x<=min){
27+
stack.push(min);
28+
min =x;
29+
}
30+
stack.push(x);
31+
}
32+
33+
public void pop() {
34+
if(min==stack.peek()){
35+
stack.pop();
36+
min= stack.pop();
37+
}else
38+
stack.pop();
39+
}
40+
41+
public int top() {
42+
return stack.peek();
43+
}
44+
45+
public int getMin() {
46+
return min;
47+
}
48+
}

0 commit comments

Comments
 (0)