← DiffPush

Implement Stack using Queue

Baseline Stack and Queues · Learning O(1) push, O(n) pop · O(n)

The Rotating Buffet Line

A cafeteria passes trays along a single-file line, but the chef wants the tray added most recently to be the one served next — the opposite of how the line naturally works. The workaround: whenever a serving is requested, the kitchen cycles every tray except the newest around the line once, so the newest tray arrives at the serving end. Implement this controller so push stays cheap and each pop serves the freshest tray.

Input: A list of operations, each either ["push", value] to insert or ["pop"] to remove.

Output: Return the list of values produced by every pop operation, in order; a pop on an empty structure yields -1.

Constraints

Examples

Example 1

Input: {"operations":[["push",1],["push",2],["pop"],["push",3],["pop"],["pop"]]}
Output: [2,3,1]
Pop rotates 1 to the back and serves 2; afterwards 3 then 1 leave in LIFO order.

Example 2

Input: {"operations":[["push",5],["pop"],["pop"]]}
Output: [5,-1]
The lone element is served first; the second pop hits an empty queue.

Solve this in your browser →

Also on LeetCode ↗