堆盘子。设想有一堆盘子,堆太高可能会倒下来。因此,在现实生活中,盘子堆到一定高度时,我们就会另外堆一堆盘子。请实现数据结构SetOfStacks,模拟这种行为。SetOfStacks应该由多个栈组成,并且在前一个栈填满时新建一个栈。此外,SetOfStacks.push()和SetOfStacks.pop()应该与普通栈的操作方法相同(也就是说,pop()返回的值,应该跟只有一个栈时的情况一样)。 进阶:实现一个popAt(int index)方法,根据指定的子栈,执行pop操作。
当某个栈为空时,应当删除该栈。当栈中没有元素或不存在该栈时,pop,popAt 应返回 -1.
示例1:
示例2:
这道题可以说并不算难题,只需要你耐心去看题即可。我们这道题可以用vector里包含stack去做。
这道题需要特别注意,当单个栈的空间为0时,我们直接返回就好了,其他的具体的方法请看代码:
class StackOfPlates {
public:vector> heap;int size;StackOfPlates(int cap) {size = cap;}void push(int val) {if (size == 0) return ;if(heap.size() == 0) {stack temp ;heap.push_back(temp);}if(heap.back().size() < size){heap.back().push(val);}else{stack temp;heap.push_back(temp);heap.back().push(val);}}int pop() {if(heap.size() == 0) return -1;int temp = heap.back().top();heap.back().pop();if(heap.back().empty()) heap.pop_back();return temp;}int popAt(int index) {if(heap.size() <= index) return -1;if(heap[index].empty()) return -1;int temp = heap[index].top();heap[index].pop();if(heap[index].empty()) heap.erase(heap.begin()+index);return temp;}
};/*** 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);*/
复杂度分析,我们用来
这道题不难,只要沉下心来,慢慢写,就能写出来