leetcode1649堆盘子(堆盘子。设想有一堆盘子,堆太高可能会倒下来。因此,在现实生活中,盘子堆到一定高度时,我们就会另外堆一堆盘子。请实现数据结构SetOfStacks,模拟这种行为)

  堆盘子。设想有一堆盘子,堆太高可能会倒下来。因此,在现实生活中,盘子堆到一定高度时,我们就会另外堆一堆盘子。请实现数据结构SetOfStacks,模拟这种行为。SetOfStacks应该由多个栈组成,并且在前一个栈填满时新建一个栈。此外,SetOfStacks.push()和SetOfStacks.pop()应该与普通栈的操作方法相同(也就是说,pop()返回的值,应该跟只有一个栈时的情况一样)。 进阶:实现一个popAt(int index)方法,根据指定的子栈,执行pop操作。
示例1:

输入:
[“StackOfPlates”, “push”, “push”, “popAt”, “pop”, “pop”]
[[1], [1], [2], [1], [], []]
输出:
[null, null, null, 2, 1, -1]

示例2:

输入:
[“StackOfPlates”, “push”, “push”, “push”, “popAt”, “popAt”, “popAt”]
[[2], [1], [2], [3], [0], [0], [0]]
输出:
[null, null, null, null, 2, 1, 3]

思路:
  可以用List<Stack>这个数据结构来存放动态变化的栈,通过使用List和Stack中的remove()、push()、pop()等API方便地实现动态栈。
class StackOfPlates {
	//存储多个栈的容器
    private List<Stack<Integer>> stackList;
    //盘子高度的最大值
    private int cup;
    
    public StackOfPlates(int cap) {
    	//构造函数完成初始化的功能
        this.cup = cap;
        stackList = new ArrayList<>();
    }

    public void push(int val) {
        if (cup <= 0) {
            return;
        }
		//这两个逻辑或的条件一定不能反过来写,只有栈不为空时才能有size==cup的判断
        if (stackList.isEmpty() || stackList.get(stackList.size() - 1).size() == cup) {
        	//新建一个栈存入容器
            Stack<Integer> stack = new Stack();
            stack.push(val);
            stackList.add(stack);
            return;
        }
        //栈未达到最大值就从容器中最后一个栈的末尾入栈
        stackList.get(stackList.size() - 1).push(val);
    }

    public int pop() {
    	//直接调用已定义好的方法,下标参数为容器中最后一个栈的下标
        return popAt(stackList.size() - 1);
    }

    public int popAt(int index) {
		//下标越界
        if (index < 0 || index >= stackList.size()) {
            return -1;
        }
        //得到容器中下标对应的栈
        Stack<Integer> stack = stackList.get(index);
        //栈为空
        if (stack.isEmpty()) {
            return -1;
        }
        //出栈
        int res = stack.pop();
		//栈为空时要把这个空栈删除
        if (stack.isEmpty()) {
            stackList.remove(index);
        }
        //将出栈的元素返回
        return res;
    }
}

/**
 * Your StackOfPlates object will be instantiated and called as such:
 * StackOfPlates obj = new StackOfPlates(cap);
 * obj.push(val);
 * int param_2 = obj.pop();
 * int param_3 = obj.popAt(index);
 */
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值