循环队列比较好的实现方法-赋java代码

来源:互联网 发布:网络数字用语1 编辑:程序博客网 时间:2024/06/06 17:53

循环队列的难点在于如何判空和判满

两种方法:

1.用一个变量表示队列中元素的个数,等于容量为满。

2.开辟数组的时候多开辟一个空间,当rear=front-1的时候为满。

我认为第二种实现方法比较好,但是不太好想,代码如下:

public class CQueue {
private int[] param;
private int front;//指向队首
private int rear;//指向队尾
private int capacity = 11;//容器的容量,为了优化判空,实际的容量会-1
public CQueue() {
param = new int[capacity];

}
public CQueue(int length) {
capacity = length + 1;
param = new int[capacity];
}
//判空
public boolean isEmpty() {
return rear == front ? true : false;
}
//添加元素
public boolean add(int param) {
if ((rear + 1) % capacity == front) {
return false;
}
this.param[rear] = param;
rear = (rear + 1) % capacity;
return true;
}
//查看队首元素,如果为空返回-1
public int peek() {
if (isEmpty()) {
return -1;
}
return param[front];
}
//队首出队
public int remove() {
if (isEmpty()) {
return -1;
}
int a = param[front];
front = (front + 1) % capacity;
return a;
}
}

原创粉丝点击