I was asked to create a bounded queue class to which the conditions were the following:
Using only primitive types, implement a bounded queue to store integers. The data structure should be optimized for algorithmic runtime, memory usage, and memory throughput. No external libraries should be imported and/or used. The solution should be delivered in one class that provides the following functions:
- constructor – class should provide one method for object creation that takes an integer to set the size of the queue.
- enqueue – function should take an integer and store it in the queue if the queue isn’t full. The function should properly handle the case where the queue is already full.
- dequeue – function should return an integer if one is currently stored in the queue. The function should properly handle the case where the queue is empty.
I wrote this class but I wanted to ask for help by having someone test it as well to see if it works properly. I wrote a small main class to test it and everything seems to be working but I want another pair of eyes to look at it before I submit it. Its for an internship. Thank you in advance.
public class Queue<INT>
{
int size;
int spacesLeft;
int place= 0;
int[] Q;
public Queue(int size)
{
this.size = size;
spacesLeft = size;
Q = new int[size];
}
//enqueue - function should take an integer and store it in the queue if the queue isn't full.
//The function should properly handle the case where the queue is already full
public void enque(int newNumber) throws Exception
{
if(place <= size)
{
Q[place] = newNumber;
place++;
spacesLeft--;
}
else
throw new Exception();
}
//dequeue - function should return an integer if one is currently stored in the queue.
//The function should properly handle the case where the queue is empty.
public int deque() throws Exception
{
int dequeNum;
if(spacesLeft == size)
throw new Exception();
else
{
dequeNum = Q[0];
spacesLeft++;
}
int[] tempAry = new int[size];
for (int i=0; i < Q.length; i++)
{
if(i < size-1)
{
tempAry[i] = Q[i+1]; // put in destination
}
}
Q = tempAry;
for(int i = 0; i < Q.length; i++)
{
System.out.println("value in Q"+Q[i]);
}
return dequeNum;
}
}
Here is the implementation that as per your specifications.
Here is the source code for the same.