【问题标题】:displaying circular queue in java在java中显示循环队列
【发布时间】:2020-04-09 16:35:14
【问题描述】:

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

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

【问题讨论】:

  • 预期的行为是什么?

标签: java arrays queue


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    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 开始。您需要包含偏移量并允许环绕。
    猜你喜欢
    • 2022-01-19
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-06
    • 1970-01-01
    相关资源
    最近更新 更多