将问题转化为单个栈的出栈入栈(只对temp栈进行操作。),然后考虑栈满的时候创建新栈,栈空的时候取集合栈的栈顶。
class SetOfStacks {
public:
vector<vector<int> > setOfStacks(vector<vector<int> > ope, int size) {
// write code here
stack<stack<int> > result;
int len=ope.size();
stack<int> temp;
for(int i=0;i<len;i++){
//push
if(ope[i][0]==1){
// temp full
if(temp.size()==size){
result.push(temp);
stack<int>().swap(temp);
temp.push(ope[i][1]);
}
// temp has freespace
else
temp.push(ope[i][1]);
}
//pop
else{
// temp empty
if(temp.size()==0){
temp=result.top();
result.pop();
temp.pop();
}
// temp has element
else{
temp.pop();
}
}
}
if(temp.size())
result.push(temp);
int rows=result.size();
vector<vector<int> > ret(rows);
for(int i=rows-1;i>=0;i--){
stack<int> tmp=result.top();
result.pop();
int cols=tmp.size();
vector<int> t(cols);
for(int j=cols-1;j>=0;j--){
t[j]=tmp.top();
tmp.pop();
}
ret[i]=t;
}
return ret;
}
};


京公网安备 11010502036488号