Implement Stack using Queues
Easy
Topics
Implement a last-in-first-out (LIFO) stack using only queues. Implement MyStack with push(x), pop() (removes and returns the top element), top() (returns the top element), and empty().
Example 1
A queue serves from the front, so the newest element has to be moved there. One of the two must be.
Calls run top to bottom; the arrow shows what each one returns.
Input: operations = ["MyStack","push","push","top","pop","empty"], values = [[],[1],[2],[],[],[]] Output: [null,null,null,2,2,false]
Constraints
- 1 <= x <= 9
- At most 100 calls to push, pop, top, and empty.
- pop and top are only called on a non-empty stack.
Editorial — intuition, approach, complexity and pitfalls
Intuition
A single queue can behave like a stack if, right after each push, you rotate all the earlier elements behind the new one. Then the newest element sits at the front and dequeues first — LIFO from a FIFO structure.
Approach
- Keep one queue.
- On push, enqueue x, then dequeue-and-re-enqueue the other elements so x moves to the front.
- pop/top read the front; empty checks the size.
Dry Run
One queue, and push pays to keep the newest element at the FRONT where the queue
will hand it back first.
push 1 append -> 1 rotate 0 times queue 1
empty -> false
top -> 1
push 3 append -> 1 3 rotate 1: 3 1 queue 3 1
push 6 append -> 3 1 6 rotate 2: 1 6 3, then 6 3 1 queue 6 3 1
push 9 append -> 6 3 1 9 rotate 3: 3 1 9 6, 1 9 6 3,
then 9 6 3 1 queue 9 6 3 1
pop -> 9 queue 6 3 1
pop -> 6 queue 3 1
empty -> false
answer null|null|false|1|null|null|null|9|6|false
Follow the "push 6" row. After the append the queue reads 3 1 6 with the newest
element at the back, which is the wrong end. Two rotations -- dequeue the front,
enqueue it again -- carry the two older elements around behind the 6 and leave
6 3 1, which is the stack order.
The count is size - 1, not size. Rotating a full size times returns the queue to
exactly where it started, so the newest element would sit at the back and pop
would return the OLDEST. Rotating size - 1 times is what stops one short.
The cost is deliberately front-loaded: push is O(n) and pop, top and empty are all
O(1). The mirror-image design, two stacks making a queue, puts the cost on pop
instead. Which one you want depends on which operation dominates.Complexity
- Time — O(n) push: push rotates the queue; pop/top/empty are O(1).
- Space — O(n): the queue holds all elements.
Common Pitfalls
- Rotate exactly size-1 times so the new element ends up at the front.
Full Solution — all languages
from collections import deque
class MyStack:
def __init__(self):
self.q = deque()
def push(self, x):
self.q.append(x)
for _ in range(len(self.q) - 1):
self.q.append(self.q.popleft())
def pop(self):
return self.q.popleft()
def top(self):
return self.q[0]
def empty(self):
return not self.qimport java.util.*;
class MyStack {
Queue<Integer> q = new LinkedList<>();
public MyStack() {
}
public void push(int x) {
q.add(x);
for (int i = 0; i < q.size() - 1; i++) q.add(q.poll());
}
public int pop() {
return q.poll();
}
public int top() {
return q.peek();
}
public boolean empty() {
return q.isEmpty();
}
}#include <bits/stdc++.h>
using namespace std;
class MyStack {
queue<int> q;
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 v = q.front();
q.pop();
return v;
}
int top() {
return q.front();
}
bool empty() {
return q.empty();
}
};class MyStack {
constructor() {
this.q = [];
}
push(x) {
this.q.push(x);
for (let i = 0; i < this.q.length - 1; i++) this.q.push(this.q.shift());
}
pop() {
return this.q.shift();
}
top() {
return this.q[0];
}
empty() {
return this.q.length === 0;
}
}