题解 | 包含min函数的栈
包含min函数的栈
https://www.nowcoder.com/practice/4c776177d2c04c2494f2555c9fcc1e49
import java.util.*;
import java.util.Stack;
public class Solution {
Stack<Integer> origin=new Stack<Integer>();
Stack<Integer> orderStack =new Stack<Integer>();
Stack<Integer> other =new Stack<Integer>();
public void push(int node) {
// origin.push(node);
if(orderStack.isEmpty()){
orderStack.push(node);
}else if(orderStack.peek()<node){
while(!orderStack.isEmpty()&&orderStack.peek()<node){
other.push(orderStack.pop());
}
orderStack.push(node);
while(!other.isEmpty()){
orderStack.push(other.pop());
}
}else if(orderStack.peek()>=node){
orderStack.push(node);
}
origin.push(node);
System.out.println(origin.peek());
System.out.println(orderStack.peek());
}
public void pop() {
// 我能想到用一个索引 或者借助一个空的栈 空的栈是最简单的 这样的话 删除后 在添加就可以了
int peek=origin.pop();
while(orderStack.peek()!=peek){
other.push(orderStack.pop());
}
orderStack.pop();
while(!other.isEmpty()){
orderStack.push(other.pop());
}
}
public int top() {
return origin.peek();
}
public int min() {
return orderStack.peek();
}
}
查看30道真题和解析