How can we Implement a Stack using Queue in Java?


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.

A Queue class extends Collection interface and it supports the insert and removes operations using a first-in-first-out (FIFO). We can also implement a Stack using Queue in the below program.

Example

import java.util.*;

public class StackFromQueueTest {
   Queue queue = new LinkedList();
   public void push(int value) {
      int queueSize = queue.size();
      queue.add(value);
      for (int i = 0; i < queueSize; i++) {
         queue.add(queue.remove());
      }
   }
   public void pop() {
      System.out.println("An element removed from a stack is: " + queue.remove());
   }
   public static void main(String[] args) {
      StackFromQueueTest test = new StackFromQueueTest();
      test.push(10);
      test.push(20);
      test.push(30);
      test.push(40);
      System.out.println(test.queue);
      test.pop();
      System.out.println(test.queue);
   }
}

Output

[40, 30, 20, 10]
An element removed from a stack is: 40
[30, 20, 10]
raja
Published on 05-Aug-2019 19:10:48
Advertisements