Construct a Stack Data Structure using a Queue

It is possible to construct a stack like data structure with push and pop operations using a queue. This is one of the most frequently asked interview questions and if you are a computer science student then this is going to be really useful stuff for you. So let's see the basic concept behind this program.

Push Operation : 
  • Get a number from the user.
  • Enqueue it to the queue.

Pop Operation : 
  • Print an error message if the queue is empty.
  • Run a for loop with the condition i < number_of_elements_in_queue - 1.
  • Dequeue and enqueue the queue.
  • Outside the loop dequeue another element and save it in a variable data.
  • Return data.

Here is a pictographic representation for better understanding.


In this example program I've used only a linear queue (arrays) in order to keep it simple and short. You can use circular queues are queues using linked list to make it more efficient.



The insert and remove functions are those functions used for inserting and removing content from our data structure. It is similar to the push and pop functions of a stack.

Output :


Comments

Popular posts from this blog

Finding the Number of Trailing Zero's in Factorial of a Number

Finding the sum of N Biggest elements in Binary Search Tree

Finding a Single Number amongst Repeated Numbers [Repeated Twice]