Advertisements
Advertisements
Question
A circular queue is a linear data structure that allows data insertion at the rear and removal from the front, with the rear end connected to the front end forming a circular arrangement.
The details of the members of the class are given below:
| Class name: | CirQueue |
| Data members/instance variables: | |
| Q[ ]: | array to hold integer values |
| cap: | maximum capacity of the circular queue |
| front: | to point the index of the front |
| rear: | to point the index of the rear |
| Methods/Member functions: | |
| CirQueue(int n): | constructor to initialise cap = n, front = 0 and rear = 0 |
| void pushi(int v): | to add integers from the rear index if possible else display the message "QUEUE IS FULL" |
| int remove( ); | to remove and return the integer from front if any, else return −999 |
| void print( ): | to display the elements of the circular queue in the order of front to rear |
Specify the class CirQueue giving the details of the functions void push(int) and int remove( ). Assume that the other functions have been defined.
The main( ) function and algorithm need NOT be written.
Advertisements
Solution
public class CirQueue {
private int[] Q;
private int cap;
private int front;
private int rear;
// Constructor to initialize the circular queue
public CirQueue(int n) {
cap = n;
Q = new int[cap];
front = 0;
rear = 0;
}
public void push(int v) {
// Check if queue is full (next position after rear is
front)
if ((rear + 1) % cap == front) {
System.out.println("QUEUE IS FULL");
return;
}
// Add the element at rear position
Q[rear] =v;
// Move rear circularly
rear = (rear + 1) % cap;
}
public int remove() {
// Check if queue is empty (front equals rear)
if (front == rear) {
return -999;
}
// Get the element at front
int removedValue = Q[front];
// Move front circularly
front = (front + 1) % cap;
return removedValue;
}
push(int v) Method:
Checks if the queue is full by comparing the next rear place to the front. If the queue is full, it will display the message "QUEUE IS FULL". If not full, add the element at the rear position and use modulo operation to increase it circularly.
remove() Method:
Checks whether the queue is empty (front equals rear). If empty, returns −999, as requested. If not empty, removes the front element, increments it in a circular pattern, and returns the removed value.
Circular Nature:
The modulo operation (% cap) ensures that the front and rear pointers wrap around to 0 at the conclusion of the array. This causes the queue to behave circularly.
