目录
- 题目
- 1- 思路
- 2- 实现
- ⭐155. 最小栈——题解思路
- 3- ACM 实现
题目
- 原题连接:155. 最小栈
1- 思路
思路
- 最小栈 ——> 借助两个栈来实现
2- 实现
⭐155. 最小栈——题解思路
class MinStack {
Stack<Integer> data;
Stack<Integer> min;
public MinStack() {
data = new Stack<>();
min = new Stack<>();
}
// 判断当前元素和 min 的peek大小
public void push(int val) {
data.push(val);
if(min.isEmpty() || val<=min.peek()){
min.push(val);
}else{
min.push(min.peek());
}
}
public void pop() {
data.pop();
min.pop();
}
public int top() {
return data.peek();
}
public int getMin() {
return min.peek();
}
}
3- ACM 实现
public class MinStack {
Stack<Integer> data;
Stack<Integer> min;
public MinStack(){
data = new Stack<>();
min = new Stack<>();
}
public void push(int val){
data.push(val);
if(min.isEmpty() || val<=min.peek()){
min.push(val);
}else{
min.push(min.peek());
}
}
// pop
public void pop(){
data.pop();
min.pop();
}
// top()
public int top(){
return data.peek();
}
// getMin()
public int getMin(){
return min.peek();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
MinStack minStack = null;
while (scanner.hasNext()) {
String command = scanner.next();
if (command.equals("push")) {
int value = scanner.nextInt();
minStack.push(value);
} else if (command.equals("pop")) {
minStack.pop();
} else if(command.equals("MinStack")) {
minStack = new MinStack();
}
else if (command.equals("top")) {
System.out.println(minStack.top());
} else if (command.equals("getMin")) {
System.out.println(minStack.getMin());
}
}
scanner.close();
}
}