题目描述:
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
思路:Push操作直接压入到stack1中;pop操作这里的意思是既要返回队列头部的值,又要将其弹出队列,因此如果stack2为空,将stack1中的全部元素出栈,放到stack2中,再从stack2中弹出栈顶元素即可,如果stack2不为空,直接弹出即可。
代码:(没有加异常检测,即空队列检测)
class Solution
{
public:
void push(int node) {
stack1.push(node);
return;
}
int pop() {
int re;
if(stack2.empty()){
while(!stack1.empty()){
stack2.push(stack1.top());
stack1.pop();
}
}
re=stack2.top();
stack2.pop();
return re;
}
private:
stack<int> stack1;
stack<int> stack2;
};