Learn-dsa..in 30 days!



























CC-3 : FIFO Circular Queue Using array.

Description:

Create a FIFO Circular Queue using array for storage.

Test cases and expected outputs:

Input Parameters Expected outputs
QueueCircularArray queue=new QueueCircularArray()
queue.add(9);
queue.add(14);
queue.add(17);
queue.add(34);
queue.add(21);
Queue nodes: 9 <- 14 <- 17 <- 34 <- 21
queue.remove();
queue.remove();
queue.remove();
Queue nodes: 34 <- 21 <- 28
queue.add(55);
queue.add(63);
Queue nodes: 34 <- 21 <- 28<- 55 <- 33

Pseudocode:

The FIFO Array Circular Queue will use a fixed size array for storing data elements.
Maintain pointers to index of first and last data elements in the storage array.
The add() method:
Check if storage array is full, if so, return false.
If array is empty, increment firstIdx and lastIdx.
If lastIdx is greater than Queue size, then set lastIdx to 0; this is because we are using the array as a circular array.
Store new data at index lastIdx.
The remove() method:
If storage array is empty, return false.
If set variable removedData to data element at index firstIdx.
If Queue data element count is 1, Set firstIdx and lastIdx to -1 as the Queue will be empty after current operation.
Else if Queue size > 1, increment firstIdx to 0; this is because we are using the array as a circular array.
Return removedData.

Code:

public class QueueCircularArray {

private int qSize=5;
private int[] queue=new int[qSize];	
private int firstIdx=-1;
private int lastIdx=-1;
	
public int get() {
	if (firstIdx != -1) {
		return queue[firstIdx];
	}
	return Integer.MIN_VALUE;
}

public boolean add(int data){
	if (getSize()==qSize) {return false;}
	if (firstIdx==-1) {firstIdx++;}
	lastIdx++;
	if (lastIdx >= qSize) {lastIdx=0;}
	queue[lastIdx]=data;
	return true;
}

public int remove() {
	if (lastIdx == -1) {return Integer.MIN_VALUE;}
	int removedData=queue[firstIdx];
	if (getSize()==1) {
		queue[firstIdx]=0;
		firstIdx=-1;
		lastIdx=-1;
		return removedData;
	} 
	queue[firstIdx]=0;
	firstIdx++;
	if (firstIdx >= qSize) {firstIdx=0;}
	return removedData;
}
}

Click here to download and run code and test cases !