包含min函数的栈

来源:互联网 发布:mac显示电池百分比 编辑:程序博客网 时间:2024/06/10 09:31

定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。

建立辅助栈,如果比第一个入栈的元素小则入栈,否则不入栈,这样就保持栈顶总是最小

import java.util.Stack;public class Solution {    Stack<Integer> data = new Stack<Integer>();    Stack<Integer> min = new Stack<Integer>();    Integer temp = null;    public void push(int node) {        if(temp != null){            if(node <= temp ){                temp = node;                min.push(node);            }            data.push(node);        }else{            temp = node;            data.push(node);            min.push(node);        }    }         public void pop() {        int num = data.pop();        int num2 = min.pop();        if(num != num2){           min.push(num2);        }    }         public int top() {     return data.peek();    }         public int min() {      return min.peek(); //返回栈顶元素但不出栈    }}

0 0
原创粉丝点击