我需要为赋值创建一个队列,我给了一个模板。我需要它在数据变满时自动将数据重新分配到新数组中,但我无法弄清楚如何做到这一点。这是我正在努力的部分:
// Expand the array to double its current size if the queue is full and reallocate the array
private expand()
{
String[]newArray = new String[maxSize*2];
int temp = -1;
for (int i=head; i<=tail; i++)
{
temp = temp +1;
newArray[temp] = data[i];
}
data = newArray;
return ;
}
ArrayQueue类如下:
public class ArrayQueue implements JFQueue
{
private int maxSize = 5; //maximum queue size
int head; //Location of the head or first element
int tail; //Location of the last element
int size; //number of elements in the queue
String[] data; //Array to hold the data
/** Constructor
@param maxSize sets up the maximum queue size
*/
public ArrayQueue(int maxSize)
{
maxSize = maxSize;
head = -1;
tail = -1;
size = 0;
data = new String[maxSize];
}
// Add an element to the end of the queue
public boolean queue(String s)
{
if (size == maxSize)
{
expand();
return false;
}
else if (tail == maxSize -1 && head != 0)
{
tail = 0;
data[tail] = s;
size = size+1;
if (head == -1){
head = 0;
}
return true;
}
else
{
size = size + 1;
tail = tail + 1;
data[tail] = s;
if (head == -1)
{
head = 0;
}
return true;
}
}
// Remove the element at the front of the queue
public String deQueue()
{
if (size == 0)
{
System.out.println("Queue is empty");
}
else if (head == maxSize -1)
{
head = 0;
size = size - 1;
}
else
{
size = size-1;
head = head + 1;
}
return data[head];
}
// Return the size of the queue
public int getSize()
{
return size;
}
// Return the size of the queue
public int getArraySize()
{
return maxSize;
}
// The traverse method verify that we correctly implemented the queue
public void traverse()
{
for(int i=0; i<size; i++)
{
System.out.println("Array Location " +(head + i)%maxSize +" Value "+
data[(head + i)%maxSize]);
}
}
// Expand the array to double its current size if the queue is full and reallocate the array
private expand()
{
String[]newArray = new String[maxSize*2];
int temp = -1;
for (int i=head; i<=tail; i++)
{
temp = temp +1;
newArray[temp] = data[i];
}
data = newArray;
return ;
}
// Reduce the size of the array to half if it is only 10% full and reallocate the array
// private compact()
// {
//
// }
}
如果我可以使扩展功能起作用,我觉得我可以找出紧凑的函数,但我不确定会返回什么,也不知道方法类型是什么。非常感谢帮助,谢谢