能返回最大值的栈

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值