Skip to content

Commit db983aa

Browse files
authored
Create MinStack.java
包含min的栈新增解法
1 parent 00cd935 commit db983aa

File tree

1 file changed

+45
-0
lines changed
  • code/offer/src/Chap4/class MinStack { private LinkedList<Integer> stack; private LinkedList<Integer> minStack;/** initialize your data structure here. *

1 file changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package Chap4;
2+
3+
import java.util.LinkedList;
4+
5+
public class MinStack {
6+
7+
private LinkedList<Integer> stack;
8+
private LinkedList<Integer> minStack;
9+
10+
/** initialize your data structure here. */
11+
public MinStack() {
12+
stack=new LinkedList<>();
13+
minStack = new LinkedList<>();
14+
}
15+
16+
public void push(int x) {
17+
stack.push(x);
18+
if (minStack.isEmpty() || x <= minStack.peek()) {
19+
minStack.push(x);
20+
}
21+
}
22+
23+
public void pop() {
24+
if (stack.isEmpty()) {
25+
return;
26+
}
27+
if (stack.pop().equals(minStack.peek())) {
28+
minStack.pop();
29+
}
30+
}
31+
32+
public int top() {
33+
if (stack.isEmpty()) {
34+
return -1;
35+
}
36+
return stack.peek();
37+
}
38+
39+
public int min() {
40+
if (minStack.isEmpty()) {
41+
return -1;
42+
}
43+
return minStack.peek();
44+
}
45+
}

0 commit comments

Comments
 (0)