
Problem
Solution
Submissions
Queue using Stacks
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to implement a queue using two stacks. A queue is a FIFO (First-In-First-Out) data structure, while a stack is a LIFO (Last-In-First-Out) data structure. Your task is to implement a queue using only stack data structures and their standard operations (push, pop, peek, empty).
Example 1
- Input: Operations = ["MyQueue", "push", "push", "peek", "pop", "empty"], Values = [[], [1], [2], [], [], []]
- Output: [null, null, null, 1, 1, false]
- Explanation: MyQueue myQueue = new MyQueue(); // Initialize queue
myQueue.push(1); // Queue: [1]
myQueue.push(2); // Queue: [1, 2]
myQueue.peek(); // Return 1, queue: [1, 2]
myQueue.pop(); // Return 1, queue: [2]
myQueue.empty(); // Return false, queue: [2]
Example 2
- Input: Operations = ["MyQueue", "push", "pop", "empty"], Values = [[], [5], [], []]
- Output: [null, null, 5, true]
- Explanation: MyQueue myQueue = new MyQueue(); // Initialize queue
myQueue.push(5); // Queue: [5]
myQueue.pop(); // Return 5, queue: []
myQueue.empty(); // Return true, queue: []
Constraints
- Use only standard stack operations (push, pop, peek, isEmpty)
- All operations must be valid (for example, no pop or peek operations will be called on an empty queue)
- 1 ≤ number of operations ≤ 100
- 1 ≤ values pushed to queue ≤ 100
- At most 100 calls will be made to push, pop, peek, and empty
- Time Complexity: O(1) amortized for all operations
- Space Complexity: O(n), where n is the number of elements in the queue
Editorial
My Submissions
All Solutions
Lang | Status | Date | Code |
---|---|---|---|
You do not have any submissions for this problem. |
User | Lang | Status | Date | Code |
---|---|---|---|---|
No submissions found. |
Solution Hints
- Use two stacks: one for pushing elements (input stack) and one for popping elements (output stack)
- Push operation: Simply push the element onto the input stack
- Pop operation: If the output stack is empty, transfer all elements from the input stack to the output stack, then pop from the output stack
- Peek operation: Similar to pop, but return the top element of the output stack without removing it
- Empty operation: Check if both stacks are empty