PROGRAM-16
Q.Write a program to implement Queue
Operations.
import java.util.*;
class Queue
{
int a[];
int size,front,rare;
Queue(int s)
{
size=s;
a=new int[size];
front=-1;
rare=-1;
}
void Enque(int n)
{
if(rare==size-1)
System.out.println("Queue overflow");
else if(front==-1&& rare==-1)
{
front=0;
rare=0;
a[rare]=n;
}
else
{
rare++;
a[rare]=n;
}
}
int Deque()
{
if(front==-1&& rare==-1)
{
System.out.println("Queue underflow");
return -999;
}
else if(front==rare)
{
int val=a[front];
front=-1;
rare=-1;
return val;
}
else
{
int temp=a[front];
front++;
return temp;
}
}
void display()
{
if(rare==-1)
System.out.println("Queue empty");
for(int i=front;i<=rare;i++)
{
System.out.print(a[i]+" ");
}
System.out.println(" ");
}
public static void main(String args[])
{
int s;
Scanner sc=new Scanner(System.in);
System.out.println("enter the size");
s=sc.nextInt();
Queue ob=new Queue(s);
ob.Enque(5);
ob.Enque(6);
ob.Enque(7);
ob.display();
int x=ob.Deque();
System.out.println("Removed element
:"+x);
ob.display();
}
}
ALGORITHM:
1. Start.
2. Initialization:
o Create a class Queue with the following attributes:
int[] a: Array to store queue elements.
int size: Maximum size of the queue.
int front: Index of the front element in the queue.
int rare: Index of the rear element in the queue.
3. Constructor:
o Initialize size, create the array a, and set front and rare to -1 (indicating an
empty queue).
4. Enque Method (Enque(int n)):
o Check if the queue is full:
If rare is at the last index and front is at the first index, or if rare + 1
equals front, print "Queue overflow".
o If the queue is empty (both front and rare are -1):
Set front and rare to 0 and add the element n to a[rare].
o If rare is at the last index, wrap around by setting rare to 0.
o Otherwise, increment rare and add n to a[rare].
5. Deque Method (Deque()):
o Check if the queue is empty:
If both front and rare are -1, print "Queue underflow" and return -999.
o Store the value at a[front].
o If front equals rare, set both to -1 (indicating the queue is now empty).
o If front is at the last index, wrap around by setting front to 0.
o Otherwise, increment front and return the stored value.
6. Display Method (display()):
o Check if the queue is empty. If it is, print "Queue empty".
o If not empty, print elements from front to rare.
o If rare is less than front, print elements in two parts: from front to the end of
the array, and from the start of the array to rare.
7. Main Method:
o Create a queue, perform some enqueuing and dequeuing operations, and display
the state of the queue at various stages.
8.Stop.
VARIABLE TABLE:
Variable Type Description
a int[]
Array to store the elements of
the queue.
size int
Maximum number of elements
the queue can hold.
front int
Index of the front element in
the queue; -1 if empty.
rear int index of the rare element in queue.
OUTPUT: