











Implementation of Queues using two Stack in Java


How to implement Queue using two Stack in Java ?
In this page we will discuss how to implement queue using stack in java . In other words we will be making a queue in which operations such as enqueue and dequeue are done based on push and pop operations .
Let us see how to do this thing in detail.
Basic Operations of Queue
- Enqueue: When we want to add an element to the end of the queue
- Dequeue: when we want to Remove an element from the front of the queue
- IsEmpty: Check if the queue is empty
- IsFull: Check if the queue is full
- Peek: Get the value of the front of the queue without removing it
ALGORITHMS:
- ENQUEUE:
static void addqueue(int a)
{
// Move all elements from p1 to p2
while (!p1.isEmpty())
{
p2.push(p1.pop());
}
p1.push(a);
while (!p2.isEmpty())
{
p1.push(p2.pop());
}
}
- DEQUEUE:
static int deletequeue()
{
// first stack is empty
if (p1.isEmpty())
{
System.out.println(“empty queue”);
}
int a = p1.peek();
p1.pop();
return a;
}
Java code to implement queue using stacks :
// Java program to implement Queue using stacks
import java.util.*;
class prepinsta
{
static class Queue
{
static Stack<Integer> p1 = new Stack<Integer>();
static Stack<Integer> p2 = new Stack<Integer>();
static void addqueue(int a)
{
// Move all elements from p1 to p2
while (!p1.isEmpty())
{
p2.push(p1.pop());
}
p1.push(a);
while (!p2.isEmpty())
{
p1.push(p2.pop());
}
}
// Dequeue an item from the queue
static int deletequeue()
{
// first stack is empty
if (p1.isEmpty())
{
System.out.println(“empty queue”);
}
// Return top of p1
int a = p1.peek();
p1.pop();
return a;
}
}
public static void main(String[] args)
{
Queue queue = new Queue();
queue.addqueue(2);
queue.addqueue(4);
queue.addqueue(6);
queue.addqueue(8);
System.out.println(queue.deletequeue());
System.out.println(queue.deletequeue());
System.out.println(queue.deletequeue());
System.out.println(queue.deletequeue());
}
}
Output:
2
4
6
8
Login/Signup to comment