将两个栈分别命名为stack1、stack2.添加是正常入栈至stack1.弹出时,将stack1所有远处弹出至stack2,此时stack2栈顶即为要被弹出的元素。弹出后再将stack2的元素依次弹出至stack1即可。
class CQueue {
public:
stack<int> stack1;
stack<int> stack2;
CQueue()
{
}
void appendTail(int value)
{
stack1.push(value);
}
int deleteHead()
{
int temp;
if(stack1.size()==0)
{
return -1;
}
else if(stack1.size()==1)
{
temp=stack1.top();
stack1.pop();
return temp;
}
else
{
while(stack1.size()!=0)
{
stack2.push(stack1.top());
stack1.pop();
}
temp=stack2.top();
stack2.pop();
while(stack2.size()!=0)
{
stack1.push(stack2.top());
stack2.pop();
}
return temp;
}
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/