Tutorialspoint
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)
QueueStackTutorialspointTech Mahindra
Editorial

Login to view the detailed solution and explanation for this problem.

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.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

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

Steps to solve by this approach:

 Step 1: Use two queues to implement the stack functionality.
 Step 2: For push operation, move all elements from queue1 to queue2 temporarily.
 Step 3: Add the new element to the now-empty queue1, so it's at the front.
 Step 4: Move all elements back from queue2 to queue1.
 Step 5: For pop and top operations, work with the front of queue1 directly.
 Step 6: The isEmpty operation simply checks if queue1 is empty.
 Step 7: This approach ensures the most recently added element is always at the front of queue1.

Submitted Code :