算法思路,设计两个栈,一个只存储普通栈的最小值,如果普通栈中的最小值要输出时,将其最小栈的值也进行pop(),实现方式如下:
package com.stack;
import java.util.Stack;
public class MinStack {
private Stack<Integer> minStack;
private Stack<Integer> stack;
public MinStack(){
this.minStack = new Stack<>();
this.stack = new Stack<>();
}
/**
* 设置加入数据,如果min的小栈为空或者当前的顶端数据大于要压入的data,则将新数据压入最小栈中。
* @param data
*/
public void push(int data){
if(minStack.isEmpty() || minStack.peek() >= data){
minStack.push(data);
}
stack.push(data);
}
public int pop(){
Integer num = stack.peek();
if(num.equals(minStack.peek())){
minStack.pop();
}
stack.pop();
return num;
}
public int top(){
return stack.peek();
}
public int min(){
return minStack.peek();
}
}