How can we Implement a Queue using Stack in Java?


A Queue class extends Collection interface and it supports the insert and removes operations using a first-in-first-out (FIFO). A Stack is a subclass of Vector class and it represents last-in-first-out (LIFO) stack of objects.

The last element added at the top of the stack (In) can be the first element to be removed (Out) from the stack. We can also implement a Queue using Stack in the below program.

Example

import java.util.*;
public class QueueUsingStackTest {
   private Stack stack1 = new Stack<>();
   private Stack stack2 = new Stack<>();
   public void enqueue(int element) {
      stack1.push(element);
      System.out.println(element + " inserted");
   }
   public void dequeue() {
      if(stack2.isEmpty()) {
         while (!stack1.isEmpty()) {
            stack2.push(stack1.pop());
         }
      }
      System.out.println(stack2.pop() + " removed");
   }
   public static void main(String args[]) {
      QueueUsingStackTest test = new QueueUsingStackTest();
      test.enqueue(10);
      test.enqueue(50);
      test.enqueue(100);
      test.dequeue();
   }
}

Output

10 inserted
50 inserted
100 inserted
10 removed

Updated on: 23-Nov-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements