In: Computer Science
JAVA:
Implement a Queue ADT using a circular array with 5 string elements. Create a Queue object and try various operations below.
Queue myQueue = new Queue();
myQueue.enqueue(“CPS 123”);
myQueue.enqueue(“CPS 223”);
myQueue.enqueue(“CPS 323”);
myQueue.dequeue();
myQueue.enqueue(“CPS 113”);
myQueue.enqueue(“CPS 153”);
string course = myQueue.front(); // course should be CPS 223
size = myQueue.size(); // size should be 4
// output course and size
public class Queue {
int front,rear;
String arr[];
int size;
int count = 0;
Queue(){
arr = new String[5]; //
size = 5; //set default size as 5
front = rear = -1; // set front rear to -1
}
void enqueue(String value){
if ((front == 0 && rear == size-1) || (rear ==
(front-1)%(size-1)))
{
System.out.println("\nQueue is Full");
return;
}
else if (front == -1) /* Insert First Element */
{
front = rear = 0;
arr[rear] = value;
}
else if (rear == size-1 && front != 0)
{
rear = 0;
arr[rear] = value;
}
else
{
rear++;
arr[rear] = value;
}
count++;
}
String dequeue(){
if (front == -1)
{
System.out.println("\nQueue is Empty");
return null;
}
String data = arr[front];
if (front == rear)
{
front = -1;
rear = -1;
}
else if (front == size-1)
front = 0;
else
front++;
count--;
return data;
}
String front(){
return arr[front];
}
int size(){
return count;
}
public static void main(String[] args) {
Queue myQueue = new Queue();
myQueue.enqueue("CPS 123");
myQueue.enqueue("CPS 223");
myQueue.enqueue("CPS 323");
myQueue.dequeue();
myQueue.enqueue("CPS 113");
myQueue.enqueue("CPS 153");
String course = myQueue.front(); // course should be CPS 223
int size = myQueue.size(); // size should be 4
System.out.println("Course: "+course);
System.out.println("size: "+size);
}
}
/* OUTPUT */
/*PLEASE UPVOTE */