---
title: "How to create a Queue using two Stack in Java."  
description: "How to create a Queue using two Stack in Java."  
author: "Erick Wilsom"  
published: 2022-11-01  
canonical: https://answers.mindstick.com/qa/98636/how-to-create-a-queue-using-two-stack-in-java  
category: "java"  
tags: ["java programming", "pythons"]  
reading_time: 3 minutes  

---

# How to create a Queue using two Stack in Java.

I want create a [queue using two stack](https://www.mindstick.com/forum/157177/how-to-create-queue-using-two-stack-in-php) in [java](https://www.mindstick.com/interview/23422/marker-interface-in-java) language.

## Answers

### Answer by Mukul Goenka

```java
import java.util.*;

class GFG
{
	static class Queue
	{
		static Stack<Integer> s1 = new Stack<Integer>();
		static Stack<Integer> s2 = new Stack<Integer>();
		static void enQueue(int x)
		{
			// Move all elements from s1 to s2
			while (!s1.isEmpty())
			{
				s2.push(s1.pop());
				//s1.pop();
			}
			// Push item into s1
			s1.push(x);
			// Push everything back to s1
			while (!s2.isEmpty())
			{
				s1.push(s2.pop());
				//s2.pop();
			}
		}
		// Dequeue an item from the queue
		static int deQueue()
		{
			// if first stack is empty
			if (s1.isEmpty())
			{
				System.out.println('Q is Empty');
				System.exit(0);
			}
			// Return top of s1
			int x = s1.peek();
			s1.pop();
			return x;
		}
	};
	// Driver code
	public static void main(String[] args)
	{
		Queue q = new Queue();
		q.enQueue(1);
		q.enQueue(2);
		q.enQueue(3);
		System.out.println(q.deQueue());
		System.out.println(q.deQueue());
		System.out.println(q.deQueue());
	}
}
```

## Output:

1 2 3

### Answer by Steilla Mitchel

```java
public class MyStack<T> {

    // inner generic Node class
    private class Node<T> {
        T data;
        Node<T> next;

        public Node(T data) {
            this.data = data;
        }
    }

    private Node<T> head;
    private int size;

    public void push(T e) {
        Node<T> newElem = new Node(e);

        if(head == null) {
            head = newElem;
        } else {
            newElem.next = head;
            head = newElem;     // new elem on the top of the stack
        }

        size++;
    }

    public T pop() {
        if(head == null)
            return null;

        T elem = head.data;
        head = head.next;   // top of the stack is head.next

        size--;

        return elem;
    }

    public int size() {
        return size;
    }

    public boolean isEmpty() {
        return size == 0;
    }

    public void printStack() {
        System.out.print('Stack: ');

        if(size == 0)
            System.out.print('Empty !');
        else
            for(Node<T> temp = head; temp != null; temp = temp.next)
                System.out.printf('%s ', temp.data);

        System.out.printf('\n');
    }
}
```

### Answer by user

Hello

I can't help's to you.

Please find another options.

### Answer by user

Hello

I can't help's to you.

Please find another options.

### Answer by Sanjay Goenka

I am write this program in python language.

```python
class Queue_Two_Stacks():

    def __init__(self):
        self.stack_1 = []
        self.stack_2 = []

    def enqueue(self, item):
        self.stack_1.append(item)

    def dequeue(self):
        if len(self.stack_2) == 0:
        # If stack_1 is empty, raise an error
            if len(self.stack_1) == 0:
                raise IndexError('Can't dequeue from empty queue!')

        # while stack_1 is not empty,
        # move items from stack_1 to stack_2, reversing order
            while len(self.stack_1) > 0:
                last_stack_1_item = self.stack_1.pop()
                self.stack_2.append(last_stack_1_item)
        # return the last item in stack_2, which is the first
        # item that entered stack_1 (FIFO!)
        return self.stack_2.pop()
```

I hope it help's to you.


---

Original Source: https://answers.mindstick.com/qa/98636/how-to-create-a-queue-using-two-stack-in-java

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
