队列实现,peek()方法错误

Queue implementation, peek() method error

这是我实现 Queue 的代码。 运行 代码出现问题,它在 peek() 方法中显示运行时错误。

public class Queue {
int size;
int frontIndex;
int backIndex;
int arr[];

Queue()
{
 size = 5;
 frontIndex =-1;
 backIndex = -1;
 arr = new int[size];
}
public int peek() {
return arr[frontIndex];
}
 public void enqueue(int data)
{
    if(isFull())
    {
    System.out.println("Queue is overflow");
    }
    else
    {   
    System.out.println("Insert " + data);
    backIndex ++;
    arr[backIndex]=data; 
    }
 }
 public static void main(String[] args) {
    Queue queue = new Queue();  
    queue.enqueue(15);
    queue.enqueue(18);      
 System.out.println("Front element of queue is " + queue.peek()); 
  } 
 }

这是我得到的错误:

"Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 5 "

您永远不会更新您的 frontIndex

您可以做的是:

frontIndex 设置为 0 而不是 -1,这样 peek() 就不会在您从队列中取出第一个元素之前抛出异常。我猜想用 -1 初始化它的原因是,你会在从队列中获取元素之前递增。当您在访问队列的第一个元素之前尝试 peek() 进入队列时,这是有问题的。

解决方法是简单地将 frontIndex 初始化为 0,然后在 从队列中获取一个值后递增它。

如果peek()实际上应该从队列中取出值,只需在peek方法中增加frontIndex

public int peek() {
    frontIndex++;
    return arr[frontIndex];
}