用两个栈实现队列
1.题目描述
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
2.思路
1.push操作插入stack1
2.pop操作:当stack2为空时,把stack1中所有元素插入stack2,pop操作对stack2进行。
3.代码
class CQueue {
public:
CQueue() {
}
void appendTail(int value) {
s1.push(value);
}
int deleteHead() {
if(s2.empty()){
while(!s1.empty()){
int temp = s1.top();
s1.pop();
s2.push(temp);
}
}
if(s2.empty()){
return -1;
}
int res = s2.top();
s2.pop();
return res;
}
private:
stack<int> s1;
stack<int> s2;
};
/**
* Your CQueue object will be instantiated and called as such:
* CQueue* obj = new CQueue();
* obj->appendTail(value);
* int param_2 = obj->deleteHead();
*/