# 225. Implement Stack using Queues

Implement the following operations of a stack using queues.

• push(x) – Push element x onto stack.
• pop() – Removes the element on top of the stack.
• top() – Get the top element.
• empty() – Return whether the stack is empty.

Example:

``````MyStack stack = new MyStack();

stack.push(1);
stack.push(2);
stack.top();   // returns 2
stack.pop();   // returns 2
stack.empty(); // returns false
``````

Notes:

• You must use  only  standard operations of a queue – which means only `push to back``peek/pop from front``size`, and `is empty` operations are valid.
• Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque (double-ended queue), as long as you use only standard operations of a queue.
• You may assume that all operations are valid (for example, no pop or top operations will be called on an empty stack).

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and all test cases.

``````class MyStack {
public:
MyStack() {}
void push(int x) {
q2.push(x);
while (q2.size() > 1) {
q1.push(q2.front()); q2.pop();
}
}
int pop() {
int x = top(); q2.pop();
return x;
}
int top() {
if (q2.empty()) {
for (int i = 0; i < (int)q1.size() - 1; ++i) {
q1.push(q1.front()); q1.pop();
}
q2.push(q1.front()); q1.pop();
}
return q2.front();
}
bool empty() {
return q1.empty() && q2.empty();
}
private:
queue<int> q1, q2;
};
``````

``````class MyStack {
public:
MyStack() {}
void push(int x) {
q.push(x);
for (int i = 0; i < (int)q.size() - 1; ++i) {
q.push(q.front()); q.pop();
}
}
int pop() {
int x = q.front(); q.pop();
return x;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
private:
queue<int> q;
};
``````

Implement Queue using Stacks

https://leetcode.com/problems/implement-stack-using-queues/

https://leetcode.com/problems/implement-stack-using-queues/discuss/62527/A-simple-C%2B%2B-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation