输入:无
要求:请仅使用两个队列实现一个栈,栈应该支持一般栈的全部四种操作:push、pop、top 和 empty。
输出:实现一个符合上述操作要求的栈类 MyStack
思路:两个队列来回倒腾,注意每次入栈就交换一次存储队列,使其时刻先入栈的元素在栈顶。
class MyStack {
private:
std::queue<int> q1; //主栈
std::queue<int> q2; //辅助栈
public:
MyStack() {
}
// push 是最复杂的操作 (O(n)) 目的是始终让最后进入的元素出现在q1队头
void push(int x) {
q2.push(x);
while (!q1.empty()) {
q2.push(q1.front());
q1.pop();
}
q1.swap(q2);
}
int pop() {
int ans = q1.front();
q1.pop();
return ans;
}
int top() {
return q1.front();
}
bool empty() {
return q1.empty();
}
};
3915

被折叠的 条评论
为什么被折叠?



