题意:实现带有min函数的栈
思路:用两个栈,一个num栈,一个min栈,当压入一个数字时候,若是比min栈中最小值大,那么min栈依然压入min栈栈顶的数字,否则,压入当前待压入的值。
代码:
package MianShiTi_21;
import java.util.Stack;
public class MianShiTi_21 {
static Stack<Integer> numStack = new Stack<>();
static Stack<Integer> minStack = new Stack<>();
public static void push(int node) {
if(minStack.empty()){
minStack.push(node);
numStack.push(node);
}else{
int tempNode = minStack.peek();
if(node >= tempNode){
minStack.push(tempNode);
numStack.push(node);
}else{
minStack.push(node);
numStack.push(node);
}
}
}
public static void pop() {
if(!numStack.isEmpty() && !minStack.isEmpty()){
numStack.pop();
minStack.pop();
}
}
public static int min() {
if(minStack.isEmpty()){
return 0;
}
return minStack.peek();
}
public static void main(String[] args) {
push(3);
System.out.println(min()+"a");
push(4);
System.out.println(min()+"b");
push(5);
System.out.println(min()+"c");
push(1);
System.out.println(min()+"d");
push(2);
System.out.println(min()+"e");
pop();
System.out.println(min()+"f");
}
}