写一个循环队列，看看第一个代码错哪里了？为什么会报数组越界？

0
[已解决问题] 解决于 2019-12-27 17:12

package com.test;

public class MyCircularQueue {
int[] data;
int tail;
int size;

``````/** Initialize your data structure here. Set the size of the queue to be k. */
public MyCircularQueue(int k) {
data = new int[k];
tail = -1;
size = 0;

}

/** Insert an element into the circular queue. Return true if the operation is successful. */
public boolean enQueue(int value) {
if(isFull()){
return false;
}
if(isEmpty()){
}
tail = (tail+1)%data.length;
data[tail] = value;
size += 1;
return true;

}

/** Delete an element from the circular queue. Return true if the operation is successful. */
public boolean deQueue() {
if(isEmpty()){
return false;
}
tail = -1;
return true;
}
size -= 1;
return true;
}

/** Get the front item from the queue. */
public int Front() {
if(isEmpty()){
return -1;
}

}

/** Get the last item from the queue. */
public int Rear() {//报错位置在这里，报的事数组越界。
if(isEmpty()){
return -1;
}
return data[tail];
}

/** Checks whether the circular queue is empty or not. */
public boolean isEmpty() {
// return size == 0?true:false; //用这一句做返回的时候会报数组越界
}

/** Checks whether the circular queue is full or not. */
public boolean isFull() {
// return size == data.length?true:false; //用这一句做返回的时候会报数组越界

return ((tail + 1) % data.length) == head;//这一句却不会报错
}``````

}

package com.test;

public class test {
public static void main(String[] args) {
MyCircularQueue myCircularQueue = new MyCircularQueue(1);
System.out.println( myCircularQueue.enQueue(1));
System.out.println( myCircularQueue.enQueue(2));
System.out.println( myCircularQueue.enQueue(3));
System.out.println( myCircularQueue.enQueue(4));
System.out.println( myCircularQueue.Rear());
System.out.println( myCircularQueue.isFull());
System.out.println( myCircularQueue.deQueue());
System.out.println( myCircularQueue.enQueue(4));
System.out.println( myCircularQueue.Rear());//这里报错了，报数组越界
}
}

lukely | 初学一级 | 园豆：143

0
``````public boolean deQueue() {
if(isEmpty()){
return false;
}
tail = -1;
return true;
}
size -= 1;
return true;
}``````

0

public boolean deQueue() {
if(isEmpty()){
return false;
}
tail = -1;
// 这里没有将size置0，导致使用size做判断的isEmpty/isFull出现逻辑错误
return true;
}