PROBLEM

剑指 Offer 09. 用两个栈实现队列

难度 简单

MY ANSWER

栈in负责append,栈out负责delete。append时直接push进in就好,delete时先检查out是否为空,out空的话再检查in是否为空,in也空的话返回-1,否则将in里的一个个出栈并压到out里,最后弹出一个。若out非空,则直接弹出一个。

class CQueue {
public:
stack<int> in;
stack<int> out;
CQueue() {}

void appendTail(int value) {
in.push(value);
}

int deleteHead() {
if(!out.empty()) {
int tmp = out.top();
out.pop();
return tmp;
}
else {
if(in.empty()) {
return -1;
}
else {
while(!in.empty()) {
out.push(in.top());
in.pop();
}
int tmp = out.top();
out.pop();
return tmp;
}
}
}
};

/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/

/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/

BETTER SOLUTION

一样。

SUMMARY

学习用两个栈实现队列。