能返回最大值的栈

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014110320/article/details/77677629

Stack with max. Create a data structure that efficiently supports the stack operations (push and pop) and also a return-the-maximum operation. Assume the elements are reals numbers so that you can compare them.

Use two stacks, one to store all of the items and a second stack to store the maximums.

public class StackWithMax {

    private Stack<Integer> s = new Stack<>();
    private Stack<Integer> maxVal = new Stack<>();
    private int max = -100000;

    public Integer pop() {
        maxVal.pop();
        return s.pop();
    }

    public void push(Integer item) {
        if(item > max){
            max = item;
        }
        s.push(item);
        maxVal.push(max);
    } 

    public Integer getMax(){
        return maxVal.first();
    }

}

如果不想用已经实现好的栈,可以自己实现栈,如果是用数组来实现栈,可以在该类中多加一个数组Max,用来保存到目前为止栈中元素的最大值。返回最大值的时候,直接返回max的最后一个元素即可,与上边的方法原理相同。

编程之美236页3.7队列取最大值操作也提供了另一种方法,不过笔者认为既然都是新申请了空间,没有这种方法来的直观,推荐这种方法。

如果实现了栈中取最大值的程序,那么就可以实现队列中取最大值元素的方法,因为队列可以用两个栈来实现。http://blog.csdn.net/u014110320/article/details/77677242

猜你喜欢

转载自blog.csdn.net/u014110320/article/details/77677629