包含min函数的栈

来源:互联网 发布:随机化算法 编辑:程序博客网 时间:2024/06/06 20:49
定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。
import java.util.Stack;public class Solution {    Stack<Integer> s = new Stack<Integer>();//s保存栈的值    Stack<Integer> s1 = new Stack<Integer>();//s1保存最小值        public void push(int node) {    s.push(node);            if(s1.empty() || node<s1.peek()){            s1.push(node);//若添加的元素小于s1栈顶元素,则直接添加        }else{            s1.push(s1.peek());//保持s1和s的元素个数一致,若添加的元素大于最小值,则最小值仍为s1的栈顶元素        }    }        public void pop() {        if(!s.empty()){            s.pop();            s1.pop();        }            }        public int top() {        if(!s.empty()){            return s.peek();        }        return 0;            }        public int min() {       if(!s.empty()){           return s1.peek();       }       return 0;    }}

0 0