实现方法:vector+stack
push的时候保证size>0的,然后最后一个没满就直接push,满了就新增。
pop的时候看vector里面空不空,空的话返回-1,不空的话pop最后一个,正好pop完的话就删除这一个。
popAt,看看索引是不是超出去了,超去了返回-1,没超出就pop那个索引对用的栈,pop完的话就删除这个。sts.erase(sts.begin()+index);
class StackOfPlates {
public:
int size=0;
vector<stack<int>> sts;
StackOfPlates(int cap) {
size=cap;
}
void push(int val) {
if(size==0) return ;
if(sts.empty()){
stack<int> s;
s.push(val);
sts.push_back(std::move(s));
return ;
}
if((sts.end()-1)->size()<size){
(sts.end()-1)->push(val);
}
else {
stack<int> s;
s.push(val);
sts.push_back(std::move(s));
}
}
int pop() {
if(sts.empty()) return -1;
int res=-1;
if((sts.end()-1)->size()!=0){
res=(sts.end()-1)->top();
(sts.end()-1)->pop();
if((sts.end()-1)->size()==0)
sts.pop_back();
}
return res;
}
int popAt(int index) {
if(sts.size()<=index) return -1;
int res=sts[index].top();
sts[index].pop();
if(sts[index].empty()) sts.erase(sts.begin()+index);
return res;
}
};