
Problem
Solution
Submissions
Stack using Queues
Certification: Basic Level
Accuracy: 0%
Submissions: 0
Points: 5
Write a C program to implement a stack using only queue data structures. A stack is a LIFO (Last-In-First-Out) data structure, while a queue is a FIFO (First-In-First-Out) data structure. Your implementation should support the standard stack operations: push, pop, top, and empty.
Example 1
- Input: Operations = ["MyStack", "push", "push", "top", "pop", "empty"], Values = [[], [1], [2], [], [], []]
- Output: [null, null, null, 2, 2, false]
- Explanation: MyStack myStack = new MyStack(); // Initialize stack
myStack.push(1); // Stack: [1]
myStack.push(2); // Stack: [1, 2]
myStack.top(); // Return 2, stack: [1, 2]
myStack.pop(); // Return 2, stack: [1]
myStack.empty(); // Return false, stack: [1]
Example 2
- Input: Operations = ["MyStack", "push", "pop", "empty"], Values = [[], [5], [], []]
- Output: [null, null, 5, true]
- Explanation: MyStack myStack = new MyStack(); // Initialize stack
myStack.push(5); // Stack: [5]
myStack.pop(); // Return 5, stack: []
myStack.empty(); // Return true, stack: []
Constraints
- All operations must be valid (for example, no pop or peek operations will be called on an empty stack)
- 1 ≤ number of operations ≤ 100
- 1 ≤ values pushed to stack ≤ 100
- At most 100 calls will be made to push, pop, top, and empty
- Time Complexity: O(n) for push and O(1) for other operations, or O(1) for push and O(n) for pop operations, depending on the approach
- Space Complexity: O(n), where n is the number of elements in the stack
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
- Consider using two queues: one main queue and one auxiliary queue
- For the push operation, you need to ensure that the newest element becomes the first to be dequeued
- One approach is to add the new element to an empty auxiliary queue, then move all elements from the main queue to the auxiliary queue, and finally swap the two queues
- Another approach is to add the new element to the main queue, then move all elements except the last one from the main queue to the auxiliary queue, and finally move the last element back to the main queue
- For pop and top operations, simply dequeue or peek at the front of the main queue