noodleProblems/
Implement Queue using Stacks
#120

Implement Queue using Stacks

AlgorithmmediumStackQueue

Implement a **first-in, first-out (FIFO) queue** using only stack operations (push / pop / peek / size / empty on a last-in, first-out structure). The queue supports four operations:

- "push" — add an element x to the back of the queue. Returns null. - "pop" — remove and return the element at the front of the queue. - "peek" — return the element at the front without removing it. - "empty" — return true if the queue is empty, false otherwise.

You are given the operations as two parallel arrays: operations[i] is the name of the i-th operation, and values[i] is its argument list ([x] for "push", [] for the others). Apply them in order and return an array holding each operation's return value (use null for "push").

"pop" and "peek" are only called on a non-empty queue.

Example cases

  • push then drain
    in operations = ["push","push","peek","pop","empty"], values = [[1],[2],[],[],[]]
    out [null,null,1,1,false]
    Push 1 then 2; peek and pop both return 1 (FIFO front); the queue still holds 2, so empty is false.
  • interleaved
    in operations = ["push","pop","empty"], values = [[5],[],[]]
    out [null,5,true]
    Push 5, pop it back out, queue is now empty.

Constraints

  • 1 <= operations.length <= 1000
  • operations[i] is one of "push", "pop", "peek", "empty".
  • 1 <= x <= 9 for every "push".
  • At most 1000 calls total; pop/peek are only made on a non-empty queue.
Saved
operations =
["push","push","peek","pop","empty"]
values =
[[1],[2],[],[],[]]