
Problem
Solution
Submissions
Stack Using Queues
Certification: Advanced Level
Accuracy: 100%
Submissions: 1
Points: 8
Write a C# program to implement a stack using only queues. Your implementation should support the standard stack operations: push, pop, top, and isEmpty.
Example 1
- Input: push(1), push(2), top(), pop(), top(), isEmpty()
- Output: 2, 2, 1, false
- Explanation:
- After pushing 1 and 2, the top is 2.
- After popping, 2 is removed and the top becomes 1.
- The stack is not empty.
Example 2
- Input: push(3), pop(), isEmpty(), pop()
- Output: 3, true, Exception: Stack is empty
- Explanation:
- After pushing 3 and popping it, the stack becomes empty.
- Trying to pop from an empty stack should throw an exception.
Constraints
- You must use only standard queue operations: enqueue, dequeue, peek, isEmpty
- You cannot use any built-in stack implementation
- All operations must run in O(1) time complexity for pop and top, and O(n) for push
- Space Complexity: O(n)
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 queues to implement the stack
- Make sure new elements are always at the front of one of your queues
- When pushing, move all elements from the first queue to the second queue
- Add the new element, then move all elements back
- For pop and top, just work with the front of the queue