Implementation of Queue using Stack in Java

Implementation of Queue using Stack

Implementation of Queue using Stack in java is being explained in this article. Queue is a linear data structure that follows First In First our principle in which insertion is perform from rear end and deletion is done from the front end. In this article, we will discuss the implementation of Queue using Stack in Java.

Queue using stack in java

Example for implementation of Queue using Stack

Example of Queue using Stack

Steps for implementing Queue using two stacks in java:

  • Step 1: Stack1 is empty so push element 1 to stack 1.
  • step 2: Now , pop element 1 from stack 1 and push it into stack2.Then , push element 2 into stack1.
  • step 3: pop element 1 from stack2 and push it into stack1.
  • step4 : pop element 1 and 2 from stack1 and push them into stack2. Then push element 3 into stack1.
  • Step 5: pop element 1 and 2 from stack2 and push them into stack1.
  • Step 6: Now pop all elements from stack1 and print them.
 

Algorithm for implementing Queue using stack

enqueue(data)

  • While stack1 is not empty, push everything from stack1 to stack2.
  • Push value to stack1.
  • Push everything back to stack1.

dequeue()

  • In this function first we will check if the queue has some element or not.
  • If our queue is empty then we cannot delete any element from it.
  • Else if there element in the queue we will pop an element from the top of stack1.

print()

  • Initialize a for loop from zero till the top.
  • Print the element at every successful iteration.
  • In this way we can display our queue.

Code for Implementation Queue using Stack in Java

Run
import java.util.*;
class Solution
{
   static class Queue
  {
        static Stack stack1=new Stack();
        static Stack stack2=new Stack();
        static void enQueue(int value)
         {
               //move all elements from stack1 to stack2
               while(!stack1.isEmpty())
               {
                       stack2.push(stack1.pop());
                }
              //push value into stack1
              stack1.push(value);
              //push everything back to stack1
              while(!stack2.isEmpty()) {
                   stack1.push(stack2.pop());
              }
          }
       static int deQueue()
          {
                if(stack1.isEmpty()){
                          System.out.println("Queue is empty");
                    System.exit(0);
          }

        //Return top of stack1
        int value=stack1.pop();
        return value;
    }
};
public static void main(String[] args)
{
      Queue q=new Queue();
      q.enQueue(10);
      q.enQueue(20);
      q.enQueue(30);
      System.out.println(q.deQueue());
      System.out.println(q.deQueue());
      System.out.println(q.deQueue());

   }
}

Output:

10
20
30