题目链接
09. 用两个栈实现队列
思路分析
用两个栈实现队列,首先把1->2然后逐个弹出顶端元素。
class CQueue {
public:
stack<int> stack1, stack2;
CQueue() {
}
void appendTail(int value) {
stack1.push(value);
}
int deleteHead() {
std::ios::sync_with_stdio(false);
if(stack1.empty() && stack2.empty()) return -1;
if(!stack2.empty()){
int tmp = stack2.top();
stack2.pop();
return tmp;
}
while(!stack1.empty()){
int tmp = stack1.top();
stack1.pop();
stack2.push(tmp);
}
int res = stack2.top();
stack2.pop();
return res;
}
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/