отображение круговой очереди в java - PullRequest
1 голос
/ 09 апреля 2020

У меня есть следующий код, где я реализовал круговой массив. Проблема возникает, когда я пытаюсь отобразить его. Метод отображения работает хорошо, пока массив не заполнится и последний не вернется к 0. Поэтому last и first оба равны 0, а for l oop не выполняется.

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();
        }
    }
}

Любая помощь приветствуется ! Спасибо

Ответы [ 2 ]

0 голосов
/ 09 апреля 2020

Вы можете изменить l oop, чтобы он перебирал от 0 до размера. Это также устраняет проблему, когда last меньше first, поскольку элементы были удалены.

    for(int i = 0; i < currentSize; i++)
    {
        queueArray[(first + i) % queueArray.length].display();
    }
0 голосов
/ 09 апреля 2020

Просто используйте свойства самого массива для отображения:

public void display()
{
    if (isEmpty())
    {
        System.out.println("The queue is empty");
    }
    else
    {
        for(int i = 0; i < queueArray.length; i++)
        {
            queueArray[i].display();
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...