《Java数据结构与算法》笔记-CH4-4循环队列

时间:2022-03-18 21:57:35
/**
* 循环队列
*/
class Queue {
private int maxSize;
private long[] queue;
private int front;
private int rear;
private int nItems; public Queue(int size) {
maxSize = size;
queue = new long[maxSize];
front = 0;
rear = -1;
nItems = 0;
} /**
* 插入value 运行的前提条件是队列不满。满的话抛出异常
*
* @param value
* @throws Exception
*/
public void insert(long value) throws Exception {
if (isFull()) {
throw new Exception("queue is full, can not insert " + value);
}
// 当rear指针指向数组的顶端,即maxSize-1位置时,在插入数据项之前,必须绕回到数组的底端。
// 回绕操作把rear设置为-1,因此当rear加1后为0,是数组底端的下标值
if (rear == maxSize - 1) {
rear = -1;
}
// 插入操作rear队尾指针加一后,在队尾指针所指的位置处插入新的数据。然后nItem++
queue[++rear] = value;
nItems++;
} /**
* 队头移除操作 前提是队列不空,为空则抛出异常
*
* @return
* @throws Exception
*/
public long remove() throws Exception {
if (isEmpty()) {
throw new Exception("queue is empty, can not remove");
}
// 移除操作总是由front指针得到队头数据项的值,然后将front加一。
long temp = queue[front++];
// 如果进行完毕后front的值超过数组的顶端,也就是==maxSize,front就必须绕回到0位置
if (front == maxSize)
front = 0;
// 操作完毕后,nItems减一
nItems--;
return temp;
} public long peekFront() {
return queue[front];
} public boolean isEmpty() {
return nItems == 0;
} public boolean isFull() {
return nItems == maxSize;
} public int size() {
return nItems;
}
} public class QueueDemo {
public static void main(String[] args) {
Queue q = new Queue(5);
try {
for (int i = 0; i < 7; i++) {
q.insert(i);
}
} catch (Exception e) {
System.out.println(e);
} try {
for (int i = 0; i < 7; i++) {
System.out.println("removed " + q.remove() + ", and queue size is: " + q.size());
}
} catch (Exception e) {
System.out.println(e);
} }
}