Write a Java program to Implement Stack using Queues


The code demonstrates how to implement a stack using queues in Java. Let's go through the code step by step:

  • The code begins with the import statements import java.util.LinkedList; and import java.util.Queue; , which import the necessary classes from the java.util package.
  • The StackUsingQueues class is defined, serving as the entry point of the program.
  • In the main method, a MyStack object named stack_list is created. MyStack is a custom class defined later in the code.
  • Five integer values (10, 20, 30, 40, and 50) are pushed onto the stack_list using the push method.
  • The while loop is used to repeatedly pop elements from the stack until it becomes empty. The pop method is called, which removes and returns the top element of the stack.
  • The popped elements are printed using the System.out.println statement.
  • The MyStack class is defined. It has a private instance variable que of type Queue<Integer>, which is implemented as a LinkedList.
  • The constructor of MyStack initializes the que object as a new LinkedList.
  • The push method adds an element to the stack. It first adds the element to the que using the add method. Then, it rearranges the elements in the que such that the newly added element becomes the front/top of the stack. This is achieved by rotating the elements in the que using the add and remove methods in a loop.
  • The pop method removes and returns the top element of the stack using the remove method of the que.
  • The top method returns the top element of the stack without removing it using the peek method of the que.
  • The isEmpty method checks if the stack is empty by calling the isEmpty method of the que.

Source Code

import java.util.LinkedList;
import java.util.Queue;
public class StackUsingQueues
{
	public static void main(String[] args)
	{
		MyStack stack_list = new MyStack();
		stack_list.push(10);
		stack_list.push(20);
		stack_list.push(30);
		stack_list.push(40);
		stack_list.push(50);
 
		while (!stack_list.isEmpty())
		{
			System.out.println(stack_list.pop());
		}
	}
}
class MyStack
{
	private Queue<Integer> que;
	public MyStack()
	{
		que = new LinkedList<>();
	}
 
	public void push(int value)
	{
		que.add(value);
		int size = que.size();
		while (size > 1)
		{
			que.add(que.remove());
			size--;
		}
	}
 
	public int pop()
	{
		return que.remove();
	}
 
	public int top()
	{
		return que.peek();
	}
 
	public boolean isEmpty()
	{
		return que.isEmpty();
	}
}

Output

50
40
30
20
10