思路:用两个栈实现,一个输入栈,一个输出栈
实现函数:
push(x) -- 将一个元素放入队列的尾部。
pop() -- 从队列首部移除元素。
peek() -- 返回队列首部的元素。
empty() -- 返回队列是否为空
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
//push()
void push(int x) {
stIn.push(x);
}
//pop()
int pop() {
// 只有当stOut为空的时候,再从stIn里导入数据(导入stIn全部数据)
if (stOut.empty()) {
// 从stIn导入数据直到stIn为空
while(!stIn.empty()) {
stOut.push(stIn.top());
stIn.pop();
}
}
int result = stOut.top();
stOut.pop();
return result;
}
//peek()
int peek() {
int res = this->pop(); // 直接使用已有的pop函数
stOut.push(res); // 因为pop函数弹出了元素res,所以再添加回去
return res;
}
//empty()
//当输入栈和输出栈均为空时说明队列也为空了
bool empty() {
return stIn.empty() && stOut.empty();
}
};