class CQueue {
public:
stack<int> st1,st2; //st1 做插入队列,st2 做删除队列
CQueue() {
// while(!st1.empty()) st1.pop(); //初始化,把栈中元素清空(也可以不用)
// while(!st2.empty()) st2.pop(); //初始化,把栈中元素清空(也可以不用)
}
void appendTail(int value) {
st1.push(value); //有元素来直接插入
}
int deleteHead()
{
if (st1.empty()&&st2.empty()) //如果两个队列都为空,直接返回
{
return -1;
}
else if(!st2.empty()) 如果 st2 不空,就要把 st2 先删空
{
int tp= st2.top();
st2.pop();
return tp;
}
else if(!st1.empty()&&st2.empty()) //当 st2 空了,就看 st1 空不空
{
while(!st1.empty()) //要确保把目前 st1 中的全部 push 到 st2,为了保证先进先出的
{
st2.push(st1.top());
st1.pop();
}
int tp2=st2.top();
st2.pop();
return tp2;
}
return -1;
}
};
//要保证一堆一堆地删,不然 st2 还有的,st1 的 push 到 st2 中,顺序就问题了
代码可能不够优雅,有错误望指出。