Overview
Implement a FIFO queue using only two stacks. The queue should support push, pop, peek, and empty.
Constraints
- Only use standard stack operations: push to top, pop from top, peek at top, size, isEmpty.
- All calls to
popandpeekare valid (queue is not empty).
Examples
const q = new MyQueue(); q.push(1); q.push(2); q.peek(); // => 1 q.pop(); // => 1 q.empty(); // => false
Solution
Reveal solution
class MyQueue {
constructor() { this.inStack = []; this.outStack = []; }
push(x) { this.inStack.push(x); }
pop() { this._move(); return this.outStack.pop(); }
peek() { this._move(); return this.outStack[this.outStack.length - 1]; }
empty() { return !this.inStack.length && !this.outStack.length; }
_move() { if (!this.outStack.length) while (this.inStack.length) this.outStack.push(this.inStack.pop()); }
}Resources
implement-queue-using-stacks.js
Implement Queue using Stacks
easycodingAlgorithmsStacks
Overview
Implement a FIFO queue using only two stacks. The queue should support push, pop, peek, and empty.
Constraints
- Only use standard stack operations: push to top, pop from top, peek at top, size, isEmpty.
- All calls to
popandpeekare valid (queue is not empty).
Examples
const q = new MyQueue(); q.push(1); q.push(2); q.peek(); // => 1 q.pop(); // => 1 q.empty(); // => false
Solution
Reveal solution
class MyQueue {
constructor() { this.inStack = []; this.outStack = []; }
push(x) { this.inStack.push(x); }
pop() { this._move(); return this.outStack.pop(); }
peek() { this._move(); return this.outStack[this.outStack.length - 1]; }
empty() { return !this.inStack.length && !this.outStack.length; }
_move() { if (!this.outStack.length) while (this.inStack.length) this.outStack.push(this.inStack.pop()); }
}Resources
NameTopicDifficulty
103 of 103 problems