225. Implement Stack using Queues
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to implement a stack (a LIFO data structure) using only queues (a FIFO data structure). We need to support the standard stack operations: push, pop, top, and empty. A queue's standard operations are push to back, peek/pop from front, size, and is empty. The key challenge is to reverse the FIFO behavior of a queue to achieve the LIFO behavior of a stack. The problem mentions using two queues, but a more optimized approach, which also answers the follow-up question, is to use a single queue.
Solution
Implement Stack using Queues in Python
from collections import deque
class MyStack:
def __init__(self):
# Use a single deque (double-ended queue) to simulate a queue.
self.q = deque()
def push(self, x: int) -> None:
# Get the current size of the queue.
size = len(self.q)
# Add the new element to the back of the queue (right side of deque).
self.q.append(x)
# Rotate the queue 'size' times to move the new element to the front.
# This makes the queue's front act as the stack's top.
for _ in range(size):
# Move the front element (left side) to the back (right side).
self.q.append(self.q.popleft())
def pop(self) -> int:
# The top of the stack is at the front of the queue (left side of deque).
return self.q.popleft()
def top(self) -> int:
# The top of the stack is at the front of the queue.
return self.q[0]
def empty(self) -> bool:
# The stack is empty if the queue is empty.
return not self.q
# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()
Implement Stack using Queues in Java
import java.util.Queue;
import java.util.LinkedList;
class MyStack {
// Use a single queue to implement the stack.
private Queue<Integer> q;
public MyStack() {
q = new LinkedList<>();
}
// Pushes element x to the top of the stack.
public void push(int x) {
// Get the current size of the queue.
int size = q.size();
// Add the new element to the back of the queue.
q.add(x);
// Rotate the queue 'size' times to move the new element to the front.
// This makes the queue's front act as the stack's top.
for (int i = 0; i < size; i++) {
// Move the front element to the back.
q.add(q.remove());
}
}
// Removes the element on the top of the stack and returns it.
public int pop() {
// The top of the stack is at the front of the queue.
return q.remove();
}
// Returns the element on the top of the stack.
public int top() {
// The top of the stack is at the front of the queue.
return q.peek();
}
// Returns true if the stack is empty, false otherwise.
public boolean empty() {
// The stack is empty if the queue is empty.
return q.isEmpty();
}
}
/**
* Your MyStack object will be instantiated and called as such:
* MyStack obj = new MyStack();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.top();
* boolean param_4 = obj.empty();
*/
Implement Stack using Queues in C++
class MyStack {
private:
// Use a single queue to implement the stack.
std::queue<int> q;
public:
MyStack() {
}
// Pushes element x to the top of the stack.
void push(int x) {
// Get the current size of the queue.
int size = q.size();
// Add the new element to the back of the queue.
q.push(x);
// Rotate the queue 'size' times to move the new element to the front.
// This makes the queue's front act as the stack's top.
for (int i = 0; i < size; ++i) {
// Move the front element to the back.
q.push(q.front());
q.pop();
}
}
// Removes the element on the top of the stack and returns it.
int pop() {
// The top of the stack is at the front of the queue.
int top_val = q.front();
q.pop();
return top_val;
}
// Returns the element on the top of the stack.
int top() {
// The top of the stack is at the front of the queue.
return q.front();
}
// Returns true if the stack is empty, false otherwise.
bool empty() {
// The stack is empty if the queue is empty.
return q.empty();
}
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
Implement Stack using Queues in TypeScript
class MyStack {
// Use an array as a queue.
private q: number[];
constructor() {
this.q = [];
}
// Pushes element x to the top of the stack.
push(x: number): void {
// Get the current size of the queue.
const size = this.q.length;
// Add the new element to the back of the queue.
this.q.push(x);
// Rotate the queue 'size' times to move the new element to the front.
// This makes the queue's front act as the stack's top.
for (let i = 0; i < size; i++) {
// Move the front element to the back.
// shift() removes from the front and returns it.
const front = this.q.shift();
if (front !== undefined) {
this.q.push(front);
}
}
}
// Removes the element on the top of the stack and returns it.
pop(): number {
// The top of the stack is at the front of the queue.
// shift() removes from the front and returns it.
const top = this.q.shift();
// The problem guarantees pop is called on a non-empty stack,
// so top will not be undefined.
return top!;
}
// Returns the element on the top of the stack.
top(): number {
// The top of the stack is at the front of the queue.
return this.q[0];
}
// Returns true if the stack is empty, false otherwise.
empty(): boolean {
// The stack is empty if the queue is empty.
return this.q.length === 0;
}
}
/**
* Your MyStack object will be instantiated and called as such:
* var obj = new MyStack()
* obj.push(x)
* var param_2 = obj.pop()
* var param_3 = obj.top()
* var param_4 = obj.empty()
*/
More Easy LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.