2

我修改了一个程序,该程序创建一个队列,然后向其中添加或删除项目。

我的代码中的问题是,在我删除一个项目,然后添加一个项目后,它会进入无限循环,我不知道如何防止它发生。

我的目标是仅修改 display() 方法。

这就是我显示队列的方式:

   public void display() 
   {
       int i = front;

           do {
               if (maxSize == nItems)
               {
                   if (i == size())
                       i = 0;

                   System.out.print(queArray[i++] + " ");
               }
               else if (maxSize < nItems)
               {
                   System.out.print("Too many queue items!");
                   break;
               }
               else
                   maxSize = nItems;
           }
           while (i != rear + 1 && !isEmpty());
       }

这就是我添加和删除项目的方式:

   public void insert(long j)   // put item at rear of queue
      {
      if(rear == maxSize-1)         // deal with wraparound
         rear = -1;
      queArray[++rear] = j;         // increment rear and insert
      nItems++;                     // one more item
      }

   public long remove()         // take item from front of queue
      {
      long temp = queArray[front++]; // get value and incr front
      if(front == maxSize)           // deal with wraparound
         front = 0;
      nItems--;                      // one less item
      return temp;
      }
4

1 回答 1

2

队列

这是相同的源代码。

import java.util.Arrays;

public class Queue {

    private int enqueueIndex;// Separate index to ensure enqueue happens at the end
    private int dequeueIndex;// Separate index to ensure dequeue happens at the
                            // start
    private int[] items;
    private int count;
    // Lazy to add javadocs please provide
    public Queue(int size) {
        enqueueIndex = 0;
        dequeueIndex = 0;
        items = new int[size];
    }
    // Lazy to add javadocs please provide
    public void enqueue(int newNumber) {
        if (count == items.length)
            throw new IllegalStateException();
        items[enqueueIndex] = newNumber;
        enqueueIndex = ++enqueueIndex == items.length ? 0 : enqueueIndex;
        ++count;
    }
    // Lazy to add javadocs please provide
    public int dequeue() {
        if (count == 0)
            throw new IllegalStateException();
        int item = items[dequeueIndex];
        items[dequeueIndex] = 0;
        dequeueIndex = ++dequeueIndex == items.length ? 0 : dequeueIndex;
        --count;
        return item;
    }

    @Override
    public String toString() {
        return Arrays.toString(items);
    }
}
于 2012-10-12T11:59:28.633 回答