用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )
思路:用两个栈来等效成队列。将一个栈元素弹出,是将该栈中的元素全部反序,模拟队列的头部删除元素。插入元素直接在栈的后边进行插入。
class CQueue {
private:
stack<int> out;//队列的头部
stack<int>ins;//队列的尾部
public:
CQueue() {
//清空栈中的元素
while(!out.empty())
{
out.pop();
}
while(!ins.empty())
{
ins.pop();
}
}
void appendTail(int value) {
ins.push(value);
}
int deleteHead() {
if(!out.empty())//直接删除元素 {
int del= out.top();
out.pop();
return del;
}
else{
while(!ins.empty())//将栈中元素反序,出入另一个栈中进行模拟队列头部元素删除
{
out.push(ins.top());
ins.pop();
}
if(out.empty()) return-1;
else
{
int del= out.top();
out.pop();
return del;
}
}
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/