Learn-dsa..in 30 days!



























CC-2 : FIFO Queue Using array.

Description:

Create a FIFO Queue using array for storage instead of LinkedList.

Test cases and expected outputs:

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

Pseudocode:

The FIFO Array Queue should instantiate and use a fixed size array for storing data elements. The last index of array at which data element is present also needs to be tracked.
The add() method: it adds input element to the storage array till it is full. Once the array is full, the add() method does not add the element to the array and returns false.
The remove() method: if storage array is empty, return false, else return the first element of the array and shift all data elements in the array left by 1 index.

Code:

public class QueueArray {
	
private int[] queue=new int[10];	
private int lastIdx=-1;
	
public int get() {
	if (lastIdx != -1) {
		return queue[0];
	}
	return Integer.MIN_VALUE;
}

public boolean add(int data){
	if (lastIdx == queue.length-1) {return false;}
	lastIdx++;
	queue[lastIdx]=data;
	return true;
}

public int remove() {
	if (lastIdx == -1) {return Integer.MIN_VALUE;}
	int removedData=queue[0];
	int qIdx=0;
	for (qIdx=0; qIdx < lastIdx; qIdx++) {
			queue[qIdx]=queue[qIdx+1];
	} 
	queue[lastIdx]=0;
	lastIdx--;
	return removedData;
}
}

Click here to download and run code and test cases !