Skip to content

Practice Implement Stack using Queues

Read the task, work through the examples, and check your approach against the constraints. Use the original LeetCode task for coding and submissions.

Easy#225
LeetCode Problem

Implement Stack using Queues

Problem Statement

Build MyStack with queue operations only, using two queues. push(x) adds a new top; pop() removes and returns the top; top() reads it without removal; empty() reports whether the stack is empty. pop and top calls are valid. The optional follow-up asks for a single-queue solution. Practice approach: In one queue, append a new value and rotate all older entries behind it using front removal and back insertion. The newest value becomes the front. Push takes O(n), while pop and top take O(1); storage is O(n). Test that removing the newest value reveals the preceding one.

Source: Implement Stack using Queues on LeetCode. Use the original task for its coding environment and submissions.

Examples

# Example 1

Input
["MyStack","push","push","top","pop","pop","empty"]
[[],[4],[7],[],[],[],[]]
Output
[null,null,null,7,7,4,true]
Explanation

The top is 7, and the removal order is 7 then 4.

Constraints

1 <= x <= 9
At most 100 total calls to push, pop, top, and empty.
Calls to pop and top are valid.

Related LeetCode Problems

Practice more problems similar to Implement Stack using Queues.

Review your practice with PhantomCodeAI

After trying the problem yourself, use the app to discuss your approach, complexity, and edge cases.