VOOZH about

URL: https://www.geeksforgeeks.org/dsa/implement-a-stack-using-single-queue/

⇱ Implement a stack using single queue - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Implement a stack using single queue

Last Updated : 23 Jul, 2025

We are given a queue data structure, the task is to implement a stack using a single queue.

Also Read: Stack using two queues

The idea is to keep the newly inserted element always at the front of the queue, preserving the order of previous elements by appending the new element at the back and rotating the queue by size n so that the new item is at the front.

// Push an element x in the stack s
push(s, x)
1) Let size of q be s.
1) Enqueue x to q
2) One by one Dequeue s items from queue and enqueue them.

// pop an item from stack s
pop(s)
1) Dequeue an item from q


Output
20
10

Time complexity

For Push Operations: O(n) as we need to rotate the queue to bring the newly added element to the front. ( where n is the size of the queue )
For Pop Operations: O(1)

Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: