1.    Create a class to implement a queue using a circular array[20 marks]<o:p></o:p>
 a.     The class should contain functions to
                                    i.         Insert a new value, [5 marks]
                                  ii.         Delete a value. [5 marks]
import java.util.ArrayList;
class Queue{
private int queueSize, frontIndex, rearIndex;
private ArrayList<Integer> queue = new ArrayList<Integer>();
Queue(int size)
{
    this.queueSize = size;
    this.frontIndex = this.rearIndex = -1;
}
public void enQueue(int data)
{Â Â Â
    if((frontIndex == 0 && rearIndex == size - 1) ||
      (rearIndex == (frontIndex - 1) % (size - 1))){
        System.out.print("Queue is full");}Â
    else if(frontIndex == -1){
        frontIndex = 0;
        rearIndex = 0;
        queue.add(rearIndex, data);}Â
    else if(rearIndex == size - 1 && frontIndex != 0){rearIndex = 0;
 queue.set(rearIndex, data);}
     else{ rearIndex = (rearIndex + 1); Â
        if(frontIndex <= rearIndex){queue.add(rearIndex, data);}
        else {queue.set(rearIndex, data);}
    }
}
 public int deQueue(){
    int temp;
    if(frontIndex == -1){
        System.out.print("Queue is Empty");
        return -1;}
     temp = queue.get(frontIndex);Â
    if(frontIndex == rearIndex){
frontIndex = -1;
rearIndex = -1;}Â
    else if(front == size - 1){frontIndex = 0;}
    else{frontIndex = frontIndex + 1;}   Â
    return temp;}
public void displayQueue(){Â Â Â Â Â
    if(frontIndex == -1)  {
        System.out.print("Queue is Empty");
        return; }Â
    System.out.print("Number of elements in the circular queue are: ");
     if(rearIndex >= frontIndex)    {
        for(int i = frontIndex; i <= rearIndex; i++){
            System.out.print(queue.get(i));
            System.out.print(" ");        }
        System.out.println();}
else    {
        for(int i = frontIndex; i < queueSize; i++)       {
            System.out.print(queue.get(i));
            System.out.print(" ");        }
        for(int i = 0; i <= rearIndex; i++)        {
            System.out.print(queue.get(i));
            System.out.print(" ");        }
        System.out.println();    } }
public static void main(String[] args){
    CircularQueue q = new CircularQueue(5);    Â
    q.enQueue(14);
    q.enQueue(22);
    q.enQueue(13);
    q.enQueue(-6);    Â
    q.displayQueue();
     int x = q.deQueue();
    if(x != -1)    {
        System.out.print("Deleted value = ");
        System.out.println(x);    }
x = q.deQueue();
    if(x != -1)    {
        System.out.print("Deleted value = ");
        System.out.println(x);    }
     q.displayQueue();
         q.enQueue(9);
    q.enQueue(20);
    q.enQueue(5);    Â
    q.displayQueue();    Â
    q.enQueue(20);}}
Comments
Leave a comment