題目:
堆盤子。設想有一堆盤子,堆太高可能會倒下來。因此,在現實生活中,盤子堆到一定高度時,我們就會另外堆一堆盤子。請實現數據結構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);
*/