Implementation of Queue using Stack in Java

Implementation of Queue Using Stack

Implementation of Queue using Stack in Java is an important problem that helps you understand how different data structures can be combined to simulate each other.

Since a queue follows FIFO (First In, First Out) and a stack follows LIFO (Last In, First Out), implementing a queue using stacks requires logical rearrangement of elements.

This topic is frequently asked in interviews because it tests your understanding of both stacks and queues. It also improves your problem-solving skills in data structure conversions.

implementing linked list using stack

Methods to Implement Queue Using Stack in Java

Here we will practice how to Implement Queue Using Stack in Java code:

  1. Using Two Stacks (Efficient and Practical)
  2. Using One Stack with Recursion (Conceptual Method)
FeatureTwo StacksOne Stack + Recursion
ComplexityO(1) amortizedO(n)
SpaceO(n)O(n) + recursion
EfficiencyHighLow
implementing queue using stack

Method to Implement Queue Using Stack in Java

Method 1: Queue Using Two Stacks

Algorithm (Two Stacks Method)

Enqueue:

  1. Push element into stack1

Dequeue:

  1. If stack2 is not empty:
    • If stack2 is not empty:
  2. Else:
    • While stack1 is not empty:
      • While stack1 is not empty:
    • Pop from stack1 and push into stack2
  3. If both stacks are empty:
    • Underflow

Java Code:

Run
import java.util.Stack;

class QueueUsingTwoStacks {

    private Stack stack1 = new Stack<>();
    private Stack stack2 = new Stack<>();

    // Enqueue operation
    public void enqueue(int value) {
        stack1.push(value);
        System.out.println(value + " inserted");
    }

    // Dequeue operation
    public int dequeue() {

        if (stack1.isEmpty() && stack2.isEmpty()) {
            System.out.println("Queue is empty (Underflow)");
            return -1;
        }

        // Move elements if needed
        if (stack2.isEmpty()) {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
        }

        return stack2.pop();
    }

    // Display queue elements
    public void display() {

        if (stack1.isEmpty() && stack2.isEmpty()) {
            System.out.println("Queue is empty");
            return;
        }

        System.out.print("Queue: ");

        // Print stack2 (top to bottom)
        for (int i = stack2.size() - 1; i >= 0; i--) {
            System.out.print(stack2.get(i) + " ");
        }

        // Print stack1 (bottom to top)
        for (int i = 0; i < stack1.size(); i++) {
            System.out.print(stack1.get(i) + " ");
        }

        System.out.println();
    }

    // Main method
    public static void main(String[] args) {

        QueueUsingTwoStacks q = new QueueUsingTwoStacks();

        q.enqueue(10);
        q.enqueue(20);
        q.enqueue(30);

        q.display();

        System.out.println("Removed: " + q.dequeue());
        System.out.println("Removed: " + q.dequeue());

        q.display();

        q.enqueue(40);

        q.display();
    }
}

Input:

enqueue(10)
enqueue(20)
enqueue(30)
dequeue()
dequeue()
enqueue(40)

Output:

10 inserted
20 inserted
30 inserted
Queue: 10 20 30
Removed: 10
Removed: 20
Queue: 30
40 inserted
Queue: 30 40

Learn DSA

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Method to Implement Queue Using Stack in Java

Method 2: Queue Using One Stack (Recursion Method)

Algorithm (Recursion Method)

Enqueue:

  1. Push element into stack

Dequeue:

  1. If stack is empty:
    • Underflow
  2. Pop top element → temp
  3. If stack is empty now:
    • Return temp (bottom element)
  4. Else:
    • result = dequeue()
    • Push temp back
    • Return result

Java Code:

Run

import java.util.Stack;

class QueueUsingOneStack {

    private Stack stack = new Stack<>();

    // Enqueue
    public void enqueue(int value) {
        stack.push(value);
        System.out.println(value + " inserted");
    }

    // Dequeue using recursion
    public int dequeue() {

        if (stack.isEmpty()) {
            System.out.println("Queue is empty (Underflow)");
            return -1;
        }

        int top = stack.pop();

        // If this is last element
        if (stack.isEmpty()) {
            return top;
        }

        int result = dequeue();

        // Push back other elements
        stack.push(top);

        return result;
    }

    // Display
    public void display() {

        if (stack.isEmpty()) {
            System.out.println("Queue is empty");
            return;
        }

        System.out.print("Queue: ");

        for (int i = 0; i < stack.size(); i++) {
            System.out.print(stack.get(i) + " ");
        }

        System.out.println();
    }

    // Main method
    public static void main(String[] args) {

        QueueUsingOneStack q = new QueueUsingOneStack();

        q.enqueue(5);
        q.enqueue(15);
        q.enqueue(25);

        q.display();

        System.out.println("Removed: " + q.dequeue());

        q.display();

        q.enqueue(35);

        q.display();
    }
}

Input:

enqueue(5)
enqueue(15)
enqueue(25)
dequeue()
enqueue(35)

Output:

5 inserted
15 inserted
25 inserted
Queue: 5 15 25
Removed: 5
Queue: 15 25
35 inserted
Queue: 15 25 35

Points to remember:

Before operations, check:

  1. Stack is not empty (for dequeue)
  2. Avoid deep recursion
  3. Handle underflow
  4. Prevent null references

Example:

if (stack.isEmpty()) {
    System.out.println("Queue is empty");
}

Frequently Asked Questions

Answer:

It is a method of creating a queue by using stack operations to maintain FIFO order.

Answer:

Using two stacks is the most efficient and commonly used method.

Answer:

Enqueue is O(1), dequeue is O(1) amortized using two stacks.

Answer:

Yes, using recursion, but it is less efficient and not recommended for large data.

Answer:

Mostly for learning and interviews. Real systems prefer built in queue structures.

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription

Stacks

  • Introduction to Stack in Data Structure
    Click Here
  • Operations on a Stack
    Click Here
  • Stack: Infix, Prefix and Postfix conversions
    Click Here
  • Stack Representation in –
    C | C++ | Java
  • Representation of a Stack as an Array. –
    C | C++ | Java
  • Representation of a Stack as a Linked List. –
    C | C++ | Java
  • Infix to Postfix Conversion –
    C | C++ | Java
  • Infix to prefix conversion in –
    C | C++ | Java
  • Postfix to Prefix Conversion in –
    C | C++ | Java

Queues

  • Queues in Data Structures (Introduction)
    Click Here
  • Queues Program in C and implementation
    Click Here
  • Implementation of Queues using Arrays | C Program
    Click Here
  • Types of Queues in Data Structure
    Click Here
  • Application of Queue Data Structure
    Click Here
  • Insertion in Queues Program (Enqueuing) –
    C | C++ | Java
  • Deletion (Removal) in Queues Program(Dequeuing) –
    C | C++ | Java
  • Reverse a Queue –
    C | C++ | Java
  • Queues using Linked Lists –
    C | C++ | Java
  • Implement Queue using Stack –
    C | C++ | Java
  • Implement Queue using two Stacks –
    C | C++ | Java

Circular Queues

Priority Queue

  • Application of Priority Queue
  • Priority Queue Example
  • Priority Queue Introduction –
    C | C++ | Java
  • Priority Queue Implementation using Array –
    C | C++ | Java
  • Priority Queue using Linked List –
    C | C++ | Java
  • Priority Queue Insertion and Deletion-
    C | C++ | Java

Stacks

Queues

Circular Queues

Priority Queue

  • Application of Priority Queue
  • Priority Queue Example
  • Priority Queue Introduction – C | C++ | Java
  • Priority Queue Implementation using Array – C | C++ | Java
  • Priority Queue using Linked List – C | C++ | Java
  • Priority Queue Insertion and Deletion- C | C++ | Java