#232
Easy Algorithms Implement queue using stacks
Stack Design Queue
69.4% acceptance
Jan 12, 2026
8564
486
Implement a first in first out (FIFO) queue using only two stacks. The implemented queue should support all the functions of a normal queue (push, peek, pop, and empty).
Implement the MyQueue class:
void push(int x) Pushes element x to the back of the queue.
int pop() Removes the element from the front of the queue and returns it.
int peek() Returns the element at the front of the queue.
boolean empty() Returns true if the queue is empty, false otherwise.
Notes:
You must use only standard operations of a stack, which means only push to top, peek/pop from top, size, and is empty operations are valid.
Depending on your language, the stack may not be supported natively. You may simulate a stack using a list or deque (double-ended queue) as long as you use only a stack's standard operations.
Solution
Rust
Time O(2^n)
Space O(n)
* impl MyQueue {
* fn new() -> Self {
* }
* fn push(&self, x: i32) {
* }
* fn pop(&self) -> i32 {
* }
* fn peek(&self) -> i32 {
* }
* fn empty(&self) -> bool {
* }
* }
*/
/*
* Your MyQueue object will be instantiated and called as such:
* let obj = MyQueue::new();
* obj.push(x);
* let ret_2: i32 = obj.pop();
* let ret_3: i32 = obj.peek();
* let ret_4: bool = obj.empty();
*/
pub struct MyQueue {
stack_in: Vec<i32>,
stack_out: Vec<i32>,
}
impl MyQueue {
fn new() -> Self {
MyQueue {
stack_in: Vec::new(),
stack_out: Vec::new(),
}
}
fn push(&mut self, x: i32) {
self.stack_in.push(x);
}
fn pop(&mut self) -> i32 {
self.peek();
self.stack_out.pop().unwrap()
}
fn peek(&mut self) -> i32 {
if self.stack_out.is_empty() {
while let Some(val) = self.stack_in.pop() {
self.stack_out.push(val);
}
}
*self.stack_out.last().unwrap()
}
fn empty(&self) -> bool {
self.stack_in.is_empty() && self.stack_out.is_empty()
}
}