Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Design a stack using two queues

Implement a LIFO stack using two FIFO queues. Support push, pop, top, and empty operations.

Python practice24 minStacks & QueuesAdvancedLast updated March 27, 2026

Problem statement

You are asked to implement a stack data structure using exactly two queues. The stack should support the following operations: - push(x): Push element x onto the stack. - pop(): Remove and return the element on top of the stack. If the stack is empty, return None. - top(): Return the top element without removing it. If the stack is empty, return None. - empty(): Return True if the stack is empty, False otherwise. Also provide a helper run_ops(ops) that executes a sequence of operations on a fresh stack instance and returns a list of results for operations that produce values (pop, top, empty).

Task

Build a stack using two queues and a helper runner to validate sequences of operations.

Examples

Basic push and pop

Input

run_ops([['push', 1], ['push', 2], ['pop'], ['pop'], ['empty']])

Output

[2, 1, True]

Push 1 then 2. pop returns 2 then 1. After both pops the stack is empty.

Input format

A list of operations. Each operation is a list where the first element is one of 'push', 'pop', 'top', 'empty'. 'push' includes a second element with the value.

Output format

A Python list of results (in order) for operations that return values: pop, top, and empty. Returned as a standard Python list.

Constraints

- Only use two queues (implemented as Python lists using append/pop(0) or collections style) for internal storage. - pop and top should have amortized O(n) or O(1) as appropriate depending on design; aim for correct behavior. - Do not use list methods that trivialize the queue abstraction like deque (explicit queue behavior via lists is fine). - Provide run_ops helper used by tests.

Samples

Sample 1

Input

run_ops([['push', 5], ['top'], ['push', 6], ['top'], ['pop']])

Output

[5, 6, 6]

After pushing 5, top is 5. After pushing 6, top is 6. pop removes and returns 6.