下面是实现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 "发布于 2021-08-23 10:04:07
您永远不会更新您的frontIndex。
你能做的就是:
将frontIndex设置为0而不是-1,这样在从队列中取出第一个元素之前,peek()不会抛出异常。我想,使用-1初始化它的理由是,在从队列中获取元素之前会增加。当您在访问第一个元素之前试图将peek()放入队列中时,这是有问题的。
解决方法是简单地用0初始化frontIndex,然后在之后将其增量为,然后从队列中得到一个值。
如果peek()应该实际将值从队列中取出,则只需在peek方法中简单地增加frontIndex:
public int peek() {
frontIndex++;
return arr[frontIndex];
}https://stackoverflow.com/questions/68890391
复制相似问题