How to create a Queue using two Stack in Java.

Asked 01-Nov-2022
Viewed 489 times

3 Answers


1

I am write this program in python language.

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.


1

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');
    }
}

 


1

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