Stack of Plates:在堆盘子的时候,如果一摞盘子过高就有可能𤭢了,所以在达到一定高度时需要新起一摞。写一个程序模拟这个过程,并提供一个popAt()函数,可以拿走指定一摞中的盘子。
书上提供的popAt()函数是这样的:在拿走指定一摞中的盘子后,要把后面一摞盘子中最下面的盘子挪到最上面,直到这是最后一摞盘子,但是力扣上的示例2显示并不要求这么做,只需要在这一摞空的时候移除这一摞就可以了,所以将栈用双向链表连接更合适。
还有比较坑的一点是每一摞的大小可能为0。
class StackOfPlates {
private:
list<stack<int>> StackSet;
size_t size;
public:
StackOfPlates(int cap) {
size = cap;
}
void push(int val) {
if(size == 0) return;
if(StackSet.empty() || StackSet.back().size() == size){
StackSet.push_back(stack<int>());
}
StackSet.back().push(val);
}
int pop() {
return popAt(StackSet.size() - 1);
}
int popAt(size_t index) {
int ret;
if(StackSet.empty() || index >= StackSet.size()){
ret = -1;
}
else{
list<stack<int>>::iterator iter = StackSet.begin();
while(index > 0){
iter++;
index--;
}
ret = iter->top();
iter->pop();
if(iter->empty()){
StackSet.erase(iter);
}
}
return ret;
}
};
/**
* 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);
*/
679

被折叠的 条评论
为什么被折叠?



