编写队列 初始化时发现 rear, front指向末尾的好处 <Java>

队列源程序:

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;

}


public static Boolean IsFull()
{
if (tear + 1 == front)
return true;
else
return false;
}


public int QueueSize() {

return (tear - front);
}

现象:只要在初始化一个队列后,一直进行在队尾插入元素,不会报错。

原因:在判断队列是否为满的子函数中,tear刚好指向最大的下标时,此时对其进行是否已满的判断,

因为front指向最小的下表,tear+1 !=  front ,所以没有报已满,但实际上是刚好满了。

解决方法:

一:在判断是否已满的子函数中,添加对上述情况的处理

二:初始化一个队列的时候,让 front = rear = 最大的下表值


Ps:细心观察,找出问题,解决问题


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值