Back

Implement Queue using Stacks

easy

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).

Notes:

  • You must use only standard operations of a stack: push to top, peek/pop from top, size, and is empty.
  • All the calls to pop and peek are valid.

Test Cases

Copy an input into the main harness and Run to verify
Input
push(1), push(2), peek(), pop(), empty()
Expected Output
1, 1, false

Explanation: Queue is [1,2]; peek returns 1, pop removes 1 leaving [2].

Constraints

  • 1 <= x <= 9
  • At most 100 calls will be made to push, pop, peek, and empty.

Hints

Hint 1 — click to reveal

One stack for input, one for output.

Hint 2 — click to reveal

Only move elements input -> output when the output stack is empty.

Java Compiler

Powered by OneCompiler. Starter code loads automatically — edit and hit Run.