设计一个具有getMin()功能的栈

来源:互联网 发布:ubuntu apt get 换源 编辑:程序博客网 时间:2024/05/19 02:41

设计一个具有getMin()功能的栈:
1.push、pop、getMin()时间复杂度为O(1)
2.设计栈时可以使用现有的栈结构

/** * 设计一个具有getMin()功能的栈: * 1.pop,push,getMin()时间复杂度为O(1) * 2.设计的栈可以使用现有的栈结构 * @author Nemo * */public class StackDemo {    private  Stack<Integer> stackData = new Stack<Integer>();    private  Stack<Integer> stackMin = new Stack<Integer>();    public void push(Integer data){        if(data == null){            throw new IllegalArgumentException("Illegal argument");        }        if(stackMin.isEmpty() || stackMin.peek() >=data){            this.stackMin.push(data);        }else{            this.stackMin.push(stackMin.peek());        }        this.stackData.push(data);    }    public Integer pop(){        if(stackData.isEmpty()){            throw new RuntimeException("stack is empty");        }        this.stackMin.pop();        return this.stackData.pop();    }    public Integer getMin(){        if(stackMin.isEmpty()){            throw new RuntimeException("stack is empty");        }        return stackMin.peek();    }
原创粉丝点击