我被要求创建一个有条件的队列类,其条件如下:
仅使用基本类型,实现有界队列以存储整数.应针对算法运行时,内存使用和内存吞吐量优化数据结构.不应导入和/或使用外部库.解决方案应该在一个提供以下功能的类中提供:
我写了这个课程,但我想通过让某人测试它以及看它是否正常工作来寻求帮助.我写了一个小的主要类来测试它,一切似乎都在工作但我想在提交它之前想看另一双眼睛.它是为了实习.先感谢您.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是根据您的规范实现的.
![]()
这是相同的源代码.
import java.util.Arrays;
public class Queue {
private int enqueueIndex;// Separate index to ensure enqueue happens at the end
private int dequeueIndex;// Separate index to ensure dequeue happens at the
// start
private int[] items;
private int count;
// Lazy to add javadocs please provide
public Queue(int size) {
enqueueIndex = 0;
dequeueIndex = 0;
items = new int[size];
}
// Lazy to add javadocs please provide
public void enqueue(int newNumber) {
if (count == items.length)
throw new IllegalStateException();
items[enqueueIndex] = newNumber;
enqueueIndex = ++enqueueIndex == items.length ? 0 : enqueueIndex;
++count;
}
// Lazy to add javadocs please provide
public int dequeue() {
if (count == 0)
throw new IllegalStateException();
int item = items[dequeueIndex];
items[dequeueIndex] = 0;
dequeueIndex = ++dequeueIndex == items.length ? 0 : dequeueIndex;
--count;
return item;
}
@Override
public String toString() {
return Arrays.toString(items);
}
}
Run Code Online (Sandbox Code Playgroud)