package com.test;
public class MyCircularQueue {
int[] data;
int tail;
int head;
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;
head = -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()){
head = 0;
}
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;
}
if (head == tail) {
head = -1;
tail = -1;
return true;
}
head = (head+1)%data.length;
size -= 1;
return true;
}
/** Get the front item from the queue. */
public int Front() {
if(isEmpty()){
return -1;
}
return data[head];
}
/** 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; //用这一句做返回的时候会报数组越界
return head == -1; //这一句却不会报错
}
/** 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());//这里报错了,报数组越界
}
}
求大神帮忙看看,谢谢
public boolean deQueue() {
if(isEmpty()){
return false;
}
if (head == tail) {
head = -1;
tail = -1;
return true;
}
head = (head+1)%data.length;
size -= 1;
return true;
}
从队列删除元素时if (head == tail) ,只把头和尾两个指针重置了,size -= 1;没有执行
public boolean deQueue() {
if(isEmpty()){
return false;
}
if (head == tail) {
head = -1;
tail = -1;
// 这里没有将size置0,导致使用size做判断的isEmpty/isFull出现逻辑错误
return true;
}
head = (head+1)%data.length;
size -= 1;
return true;
}
似乎没问题啊
博客园编辑器支持markdown代码高亮显示
– 小光 5年前