java编程练习题七

题目链接:https://leetcode-cn.com/problems/stack-of-plates-lcci/

 

 

class StackOfPlates3_3 {
    int cap;
    List<Stack<Integer>> stackList;

    public StackOfPlates(int cap) {
        this.cap = cap;
        stackList = new ArrayList<>();
    }
    
    public void push(int val) {
        if(cap==0) return;
        if(stackList.size()==0||stackList.get(stackList.size()-1).size()==cap){
            Stack<Integer> stack = new Stack<>();
            stack.push(val);
            stackList.add(stack);
        }else{
            stackList.get(stackList.size()-1).push(val);
        }
    }
    
    public int pop() {
        if(stackList.size()==0) return -1;
        Stack<Integer> stack = stackList.get(stackList.size()-1);
        int x = stack.pop();
        if(stack.size()==0) stackList.remove(stackList.size()-1);
        return x;
    }
    
    public int popAt(int index) {
        if(index>=stackList.size()||stackList.get(index).size()==0) return -1;
        Stack<Integer> stack = stackList.get(index);
        int x = stack.pop();
        if(stack.size()==0) stackList.remove(index);
        return x;
    }
}

 

 

 

 

 

 

 

 

 

版权声明:本文为qq_44923097原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_44923097/article/details/104973175