题目:
堆盘子。设想有一堆盘子,堆太高可能会倒下来。因此,在现实生活中,盘子堆到一定高度时,我们就会另外堆一堆盘子。请实现数据结构SetOfStacks,模拟这种行为。SetOfStacks应该由多个栈组成,并且在前一个栈填满时新建一个栈。此外,SetOfStacks.push()和SetOfStacks.pop()应该与普通栈的操作方法相同(也就是说,pop()返回的值,应该跟只有一个栈时的情况一样)。 进阶:实现一个popAt(int index)方法,根据指定的子栈,执行pop操作。
当某个栈为空时,应当删除该栈。当栈中没有元素或不存在该栈时,pop,popAt 应返回 -1.
示例:
输入:
["StackOfPlates", "push", "push", "popAt", "pop", "pop"]
[[1], [1], [2], [1], [], []]
输出:
[null, null, null, 2, 1, -1]
个人思路:
用一个列表存储栈,这样当要调用某个特定栈返回时,直接从列表中取。push时,获得列表中最后一个栈,判断它是否超过容量,如果没有就将值压入,如果超过了,就创建一个新的栈放值,然后将新栈放入列表。pop是,获得列表中最后一个栈,然后弹指,判断它是否为空,如果空了就将它移除列表(popAt同理)。
代码:
class StackOfPlates {
ArrayList<Stack<Integer>> stackList=new ArrayList();
int size;
public StackOfPlates(int cap) {
size=cap;
}
public void push(int val) {
if(size<=0){
return;
}
if(stackList.size()==0){
Stack<Integer> s=new Stack();
s.push(val);
stackList.add(s);
}else{
Stack<Integer> s=stackList.get(stackList.size()-1);
if(s.size()<size){
s.push(val);
}else{
Stack<Integer> s1=new Stack();
s1.push(val);
stackList.add(s1);
}
}
}
public int pop() {
if(stackList.size()==0){
return -1;
}else{
Stack<Integer> s=stackList.get(stackList.size()-1);
int re=s.pop();
if(s.isEmpty()){
stackList.remove(stackList.size()-1);
}
return re;
}
}
public int popAt(int index) {
if(stackList.size()-1<index){
return -1;
}else{
Stack<Integer> s=stackList.get(index);
int re=s.pop();
if(s.isEmpty()){
stackList.remove(index);
}
return re;
}
}
}
/**
* 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);
*/