第 18 天: 循环队列
对于循环队列,有多种方式来实现,这里采用的是一种牺牲一个单元来区分队空和队满,入队时少用一个队列单元,即约定以"队头指针在队尾指针的下一位置作为队满的标志"。
队满条件为:(rear+1)%QueueSize==front
队空条件为:front==rear
代码如下:
package day17;
public class CircleCharQueue {
public static final int TOTAL_SPACE = 10;
int head;
int tail;
char[] data;
public CircleCharQueue() {
data = new char[TOTAL_SPACE];
head = 0;
tail = 0;
}// Of the first constructor
/**
*********************
* Enqueue.
*
* @param paraValue The value of the new node.
*********************
*/
public void enqueue(char paraValue) {
if ((tail + 1) % TOTAL_SPACE == head) {
System.out.println("full queue");
return;
} // of if
data[tail % TOTAL_SPACE] = paraValue;
tail++;
}
/**
*********************
* Dequeue.
*
* @return The value at the head.
*********************
*/
public char dequeue() {
if (tail == head) {
System.out.println("no elenment in the queue");
} // of if
char resultValue = data[head % TOTAL_SPACE];
head++;
return resultValue;
}
public String toString() {
String resultString = "";
if (head == tail) {
return "empty";
} // Of if
for (int i = head; i < tail; i++) {
resultString += data[i % TOTAL_SPACE] + ", ";
} // Of for i
return resultString;
}
/**
*********************
* The entrance of the program.
*
* @param args Not used now.
*********************
*/
public static void main(String args[]) {
CircleCharQueue tempQueue = new CircleCharQueue();
System.out.println("Initialized, the list is: " + tempQueue.toString());
for (char i = '0'; i < '5'; i++) {
tempQueue.enqueue(i);
} // Of for i
System.out.println("Enqueue, the queue is: " + tempQueue.toString());
char tempValue = tempQueue.dequeue();
System.out.println("Dequeue " + tempValue + ", the queue is: " + tempQueue.toString());
for (char i = 'a'; i < 'f'; i++) {
tempQueue.enqueue(i);
System.out.println("Enqueue, the queue is: " + tempQueue.toString());
} // Of for i
for (int i = 0; i < 3; i++) {
tempValue = tempQueue.dequeue();
System.out.println("Dequeue " + tempValue + ", the queue is: " + tempQueue.toString());
} // Of for i
for (char i = 'A'; i < 'F'; i++) {
tempQueue.enqueue(i);
System.out.println("Enqueue, the queue is: " + tempQueue.toString());
} // Of for i
}// Of main
}// Of CircleCharQueue
其中增加元素和删除元素还是有很多的不同,要考虑到尾指针的位置,在循环队列中,尾指针那是指向末尾元素的下一个位置。于是有
在增加元素时:,这是从队列尾部进行操作,先将参数赋给当前的data[],再移动。
在删除元素时:,这是从队列的头部进行操作,头指针就是指向当前元素。