[英]displaying circular queue in java
I have the following code where I have implemented a circular array.我有以下代码,我在其中实现了一个循环数组。 The problem comes when I try to display it.当我尝试显示它时,问题就来了。 The display method works well until the array gets full and last goes back to 0. Therefore last and first are both 0 and the for loop doesn't execute. display 方法运行良好,直到数组变满并且 last 回到 0。因此 last 和 first 都是 0 并且 for 循环不执行。
public class PassengerQueue
{
private Passenger[] queueArray = new Passenger[TrainStation.WAITING_ROOM_CAPACITY];
private int first = 0;
private int last = 0;
private int maxStayInQueue = 0; //number of seconds that the passenger who stayed longest in the queue
private int maxLength = 0; //the maximum legth that was reached by the queue
private int currentSize = 0;
public void add(Passenger next)
{
//if the queue is not full - check for the circular queue
if (isFull()){
System.out.println("The queue is full");
}
else
{
queueArray[last] = next;
last = (last + 1) % queueArray.length;
currentSize++;
maxLength++;
}
}
public Passenger remove()
{
Passenger removedPassenger = null;
//if the queue array is not empty
//remove passenger
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
removedPassenger = queueArray[first];
queueArray[first] = null;
first = (first + 1) % queueArray.length;
currentSize--;
}
return removedPassenger;
}
public Boolean isEmpty()
{
return (currentSize == 0);
}
public Boolean isFull()
{
return (currentSize == queueArray.length);
}
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = first; i < last; i++)
{
queueArray[i].display();
}
}
}
Any help would be appreciated!任何帮助,将不胜感激! Thank You谢谢你
Just use the properties on the array itself to display:只需使用数组本身的属性来显示:
public void display()
{
if (isEmpty())
{
System.out.println("The queue is empty");
}
else
{
for(int i = 0; i < queueArray.length; i++)
{
queueArray[i].display();
}
}
}
You can change the loop so it iterates from 0 to size.您可以更改循环,使其从 0 迭代到 size。 This also fixes the problem where last
is less than first
because items have been removed.这也解决了last
小于first
的问题,因为项目已被删除。
for(int i = 0; i < currentSize; i++)
{
queueArray[(first + i) % queueArray.length].display();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.