09. 用两个栈实现队列
用两个栈实现一个队列。队列的声明如下,请实现它的两个函数 appendTail 和 deleteHead ,分别完成在队列尾部插入整数和在队列头部删除整数的功能。(若队列中没有元素,deleteHead 操作返回 -1 )。
解题思路
用两个栈,一个作为主栈,一个作为辅栈,入队的时候所有元素都压入主栈,出队的时候把主栈的所有元素先压入辅栈,然后读辅栈的栈顶元素,读完后栈顶元素出栈存在某一变量中,接着把辅栈的所有元素再压入主栈,最后返回变量。
写题过程中,遇到了两个错误,return之后的代码不再执行,把.size()函数直接用到循环中,但size一直在变,导致循环次数出错。
代码
class CQueue {
public:
stack<int> a;
stack<int> b;
CQueue() {
}
void appendTail(int value) {
a.push(value);
}
int deleteHead() {
int temp;
if (a.empty()==true)
return -1;
else {
int sizea=a.size();
for(int i=1;i<=sizea;i++)
{
b.push(a.top());
a.pop();
}
temp=b.top();
b.pop();
int sizeb=b.size();
for (int j=1;j<=sizeb;j++){
a.push(b.top());
b.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();
*/
优化思路
修改后,只判断b,如果是空就把a的元素压入,如果压入后还为空就返回-1,若果不空就直接返回栈顶元素,执行时间明显减少了。
代码
class CQueue {
public:
stack<int> a;
stack<int> b;
CQueue() {
}
void appendTail(int value) {
a.push(value);
}
int deleteHead() {
int temp;
if (b.empty()==true){
while(a.empty()==false){
b.push(a.top());
a.pop();
}
}
if (b.empty()==true){
return -1;
}
temp=b.top();
b.pop();
return temp;
}
};