Queue Using Two Stacks
Problem statement
Implement a first-in, first-out queue using two stacks. Process the operations in order, starting from an empty queue.
[0,value]: push value at the back and return 0 for this operation.[1,0]: remove and return the front value.[2,0]: return the front value without removing it.[3,0]: return 1 if the queue is empty, otherwise 0.
Return one integer per operation in the same order. Use only stack push, pop, top and empty/size operations to maintain queue state. Output storage does not count as a queue stack.
Function
runQueue(operations: int[][]) → int[]Examples
Example 1
operations = [[3,0],[0,5],[0,9],[2,0],[1,0],[2,0],[3,0]]return = [1,0,0,5,5,9,0]The queue starts empty, then holds [5,9]. Peek returns five; pop removes five; the next peek returns nine. It is still nonempty, so the outputs are [1,0,0,5,5,9,0].
Example 2
operations = [[0,-2],[1,0],[3,0]]return = [0,-2,1]Push minus two, remove it, then observe an empty queue. Return [0,-2,1].
Constraints
0 <= operations.length <= 500- Every operation has exactly two integer entries.
-1000000 <= operations[i][j] <= 1000000- Each operation code is 0, 1, 2 or 3.
- Every non-push operation has its second entry equal to zero.
- Pop and peek are used only when the queue is not empty.