题目:定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
package StackAndQueue;
import java.util.Stack;
//实现一个带有取最小值min方法的栈,min方法将返回当前栈中的最小值。
public class MinStack {
Stack<Integer> stack;
Stack<Integer> minstack;
public MinStack() {
// do intialization if necessary
stack=new Stack<>();
minstack=new Stack<>();
}
/*
* @param number: An integer
* @return: nothing
*/
public void push(int number) {
// write your code here
stack.push(number);
if(minstack.isEmpty()){
minstack.push(number);
}else{
if(number<=minstack.peek()){
minstack.push(number);
}
}
}
/*
* @return: An integer
*/
public int pop() {
// write your code here
int data=stack.pop();
if(data==min()){
minstack.pop();
}
return data;
}
/*
* @return: An integer
*/
public int min() {
// write your code here
return minstack.peek();
}
}