Implement Stack using two Queues in java

If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.

In this program, we will see how to implement stack using Linked List in java.
Stack is abstract data type which demonstrates Last in first out (LIFO) behavior. We will implement same behavior using two queue.
There are two most important operations of Stack:
Lets say you have two queues : queue1 , queue2

  • Push : 
    • If queue1 is empty, add elements to queue1
    • If queue1 is not empty, add all elements of queue1 to queue2 , add current element to queue1 and copy all elements of queue2 to queue1.
  • Pop : Simply remove element from queue1.

Java Program:

Lets create a java program to create stack using Linked List.
package org.arpit.java2blog;

import java.util.LinkedList;
import java.util.Queue;

public class StackUsingTwoQueues {

    Queue queue1;
    Queue queue2;
    StackUsingTwoQueues()
    {
        queue1=new LinkedList();
        queue2=new LinkedList();
    }

    // Remove value from the beginning of the list for demonstrating behaviour of stack
    public void push(int i){
        if(queue1.size()==0)
            queue1.add(i);
        else{
            int sizeOfQueue1 = queue1.size();
            // Copy elements of Queue1 to Queue2
            for(int j=0 ; j

When you run above program, you will get below output:

Element removed from LinkedList: 75
Removed element : 30
Removed element : 170

That's all about how to implement Stack using two Queues in java.

[social_share share_on="facebook,twitter,linkedin,whatsapp"][post_navigator in_same_term="true"]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.