繁体   English   中英

在 java 中显示循环队列

[英]displaying circular queue in java

我有以下代码,我在其中实现了一个循环数组。 当我尝试显示它时,问题就来了。 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();
        }
    }
}

任何帮助,将不胜感激! 谢谢你

只需使用数组本身的属性来显示:

public void display()
{
    if (isEmpty())
    {
        System.out.println("The queue is empty");
    }
    else
    {
        for(int i = 0; i < queueArray.length; i++)
        {
            queueArray[i].display();
        }
    }
}

您可以更改循环,使其从 0 迭代到 size。 这也解决了last小于first的问题,因为项目已被删除。

    for(int i = 0; i < currentSize; i++)
    {
        queueArray[(first + i) % queueArray.length].display();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM