队列源程序:
public class MyQueue
{private static int capacity = 100;
private static int front, tear;
private static Student[] list;
public MyQueue(int cap)
{
capacity = cap;
list = new Student[capacity];
// front = rear = 0; //以前都是这样写的
front = tear = cap; //现在改成这样写
}public void EnQueue(Student stu)
{
if (IsFull()) {
System.out.println("enqueue fail!");
} else {
tear = (tear + 1) % capacity;
list[tear] = stu;
}
return;
}
public Student DeQueue()
{
if (IsEmpty()) {
System.out.println("dequeue fail!");
return null;
} else {
front = (front + 1) % capacity;
return list[front];
}
}
public void Clear()
{
tear = front;
}
public static Boolean IsEmpty()
{
if (tear == front)
return true;
else
return false;
}
{
if (tear + 1 == front)
return true;
else
return false;
}
public int QueueSize() {
return (tear - front);}
}
现象:只要在初始化一个队列后,一直进行在队尾插入元素,不会报错。
原因:在判断队列是否为满的子函数中,tear刚好指向最大的下标时,此时对其进行是否已满的判断,
因为front指向最小的下表,tear+1 != front ,所以没有报已满,但实际上是刚好满了。
解决方法:
一:在判断是否已满的子函数中,添加对上述情况的处理
二:初始化一个队列的时候,让 front = rear = 最大的下表值
Ps:细心观察,找出问题,解决问题