Doubly Queue ISC Computer Science 2013 Theory
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:
Class name: Dequeue
Data 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 front end
rear: to point to the index of the rear end
Member functions:
Dequeue(int l): constructor to initialize the data members lim = l, front = rear = 0
void addFront(int val): to add integer from the front if possible else display the message "Overflow from front"
void addRear(int val): 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, void addFront(int), void addRear(int), int popFront() and int popRear(). The main() function and algorithm need not be written.
class Dequeue{
int arr[];
int lim;
int front;
int rear;
public Dequeue(int l){
lim = l;
if(lim > 100)
lim = 100;
arr = new int[100];
front = 0;
rear = 0;
}
public void addFront(int val){
if(front == 0)
System.out.println("Overflow from front");
else
arr[--front] = val;
}
public void addRear(int val){
if(rear == lim)
System.out.println("Overflow from rear");
else
arr[rear++] = val;
}
public int popFront(){
if(front < rear){
int d = arr[front++];
if(front == rear){
front = 0;
rear = 0;
}
return d;
}
return -9999;
}
public int popRear(){
if(front < rear){
int d = arr[--rear];
if(front == rear){
front = 0;
rear = 0;
}
return d;
}
return -9999;
}
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Dequeue limit: ");
int limit = Integer.parseInt(in.nextLine());
Dequeue dq = new Dequeue(limit);
while(true){
System.out.println("1. Add from front");
System.out.println("2. Add from rear");
System.out.println("3. Pop from front");
System.out.println("4. Pop from rear");
System.out.print("Enter your choice: ");
int choice = Integer.parseInt(in.nextLine());
switch(choice){
case 1:
System.out.print("Element to be added: ");
int v = Integer.parseInt(in.nextLine());
dq.addFront(v);
break;
case 2:
System.out.print("Element to be added: ");
v = Integer.parseInt(in.nextLine());
dq.addRear(v);
break;
case 3:
v = dq.popFront();
if(v == -9999)
System.out.println("Underflow from front");
else
System.out.println(v + " popped");
break;
case 4:
v = dq.popRear();
if(v == -9999)
System.out.println("Underflow from rear");
else
System.out.println(v + " popped");
break;
default:
System.out.println("Bye!");
return;
}
}
}
}
Comments
Post a Comment