//Dequeue
/*
A doubly queue is a linear data structure which enables the user to add and remove integers from either ends, i.e. from front or rear. Define a class Dequeue with the following details: [10]
Class name: DequeueData members/instance variables:
arr[ ]: array to hold up to 100 integer elements
lim: stores the limit of the dequeue
front: to point to the index of the front end
rear: to point to the index of the rear end
Member functions:
Dequeue(int t): constructor to initialize the data members lim = t; front = rear = -1
void addfront(int val): to add integer from the front if possible else display the message (“Overflow from front”) voidaddrear(intval): to add integer from the rear if possible else display the message (“Overflow from rear”)
int popfront(): returns element from front, if possible otherwise returns – 9999
int poprear(): returns element from rear, if possible otherwise returns – 9999
Specify the class Dequeue giving details of the constructor (int), void addfront(int), void addrear (int, popfront ( ) and int poprear ( ). The main function and algorithm need not be written.
SOLUTION:
public class Dequeue
{
int arr[] ;
int lim,front,rear;
Dequeue(int t)
{
lim=t; front=-1; rear=-1;
arr=new int[lim];
}
void addfront(int val)
{
if(front>-1)
arr[front--]=val;
else
System.out.print("\n Overflow from front");
}
void addrear(int val)
{
if(rear<lim-1)
arr[++rear]=val;
else
System.out.print("\n Overflow from rear");
}
int popfront()
{
if(front!=rear)
return arr[++front];
else
return -9999;
}
int poprear()
{
if(front!=rear)
return arr[rear--];
else
return -9999;
}
void show()
{
if(front==-1 && rear==-1)
System.out.println("Empty");
else
{
for(int i=front+1;i<=rear;i++)
System.out.print(arr[i]+" ");
}
}
public static void main(String arg[])
{
Dequeue ob=new Dequeue(5);
ob.addrear(10);
ob.addrear(20);
ob.addrear(30);
System.out.println();
ob.show();
System.out.println();
ob.addrear(40);
ob.addrear(50);
ob.show();
System.out.println();
System.out.println("DEleted No From Front is\t"+ob.popfront());
System.out.println();
ob.show();
System.out.println();
System.out.println("DEleted No From Rear is\t"+ob.poprear());
System.out.println();
ob. show();
}
}
Comments
Post a Comment