[Java][集合][List系列][Stack及其应用]

Stack简介

Stack是栈。它的特性是:先进后出(FILO, First In Last Out)。
java工具包中的Stack是继承于Vector(矢量队列)的,由于Vector是通过数组实现的,这就意味着,Stack也是通过数组实现的。

but:
JDK说了:Deque 接口及其实现提供了 LIFO 堆栈操作的更完整和更一致的 set,应该优先使用此 set,而非此类。例如:
Deque stack2 = new ArrayDeque();

  • Stack的继承关系
    java.lang.Object
    ↳ java.util.AbstractCollection
    ↳ java.util.AbstractList
    ↳ java.util.Vector
    ↳ java.util.Stack

使用ArrayDeque替代Stack

  public void testStack() {
    Stack<String> stack = new Stack<>();
    stack.push("1");
    stack.push("2");
    System.out.println("push 2 items: \n" + Arrays.toString(stack.toArray()));
    String s2 = stack.pop();
    System.out.println("pop 1 item: \n" + Arrays.toString(stack.toArray()));
    s2 = stack.peek();
    System.out.println("peek 1 item: \n" + Arrays.toString(stack.toArray()));

    //JDK说了:Deque 接口及其实现提供了 LIFO 堆栈操作的更完整和更一致的 set,应该优先使用此 set,而非此类。例如:
    Deque<Integer> stack2 = new ArrayDeque<Integer>();
    for (int i = 0; i < 10; i++) {
        //使用push,则是LIFO
        stack2.push(i);
    }

    System.out.println("push items: \n" + Arrays.toString(stack2.toArray()));
    stack2.poll();
    System.out.println("poll 1 item: \n" + Arrays.toString(stack2.toArray()));
    stack2.pop();
    System.out.println("pop 1 item: \n" + Arrays.toString(stack2.toArray()));
}

Stack在计算柱形图的最大连接矩形的应用

public void testStackOnSquareArea(){
    int[] height = {2,1,4,5,1,3,3};

    Stack<Integer> stack = new Stack<>();
    Stack<Integer> stack_count = new Stack<>();

    int maxArea = 0;
    int totalWidth = 0;
    int tmpHeight = 0;
    for (int i = 0; i < height.length; i++) {
        tmpHeight = height[i];

        //遇小柱,栈,计算右扩性累计矩形,找出最大者记录,相当于此小柱前的所有可能的矩形组合都计算完了
        totalWidth = 0;
        while(!stack.empty() && stack.peek().intValue() >= height[i]){
            int space = stack.pop().intValue() * (stack_count.peek().intValue() + totalWidth); //计算 
            if(space>maxArea){
                maxArea = space;
            }
            totalWidth += stack_count.pop();//记录遇小柱时,小柱的右扩累计宽,同时也是弹栈时,用于计算右扩累计宽
        }

        //否则,是递增柱或者弹栈后剩下的遇见小柱,入栈
        stack.push(height[i]);
        stack_count.push(totalWidth + 1);
    }

    //可能最后几个都是入栈,所以需要出栈处理
    int totalWidth2 = 0;
    while(!stack.empty()){
        int space = stack.pop().intValue() * (stack_count.peek().intValue() + totalWidth2); //计算
        if(space>maxArea){
            maxArea = space;
        }
        totalWidth2 += stack_count.pop();//记录遇小柱时,小柱的右扩累计宽,同时也是弹栈时,用于计算右扩累计宽
    }

    System.out.println("max area=" + maxArea);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值