1.代码:
package yrx;
public class CircleCharQueue {
/**
* The total space.One space can never be used
*/
public static final int TOTAL_SPACE = 10;
/**
* The data.
*/
char[] data;
/**
* The index for calculating the head.The actual head is head % TOTAL_SPACE.
*/
int head;
/**
* The index for calculating the tail
*/
int tail;
/**
*****************
* The constructor
*****************
*/
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("Queue full");
return;
} // Of if
data[tail % TOTAL_SPACE] = paraValue;// 入队位置
tail++;
}// Of enqueue
/**
*****************
* Dequeue
*
* @return The value at the head
*****************
*/
public char dequeue() {
if (head == tail) {// 队列为空
System.out.println("No element in the queue");
return '\0';// 空格
}
char resultValue = data[head % TOTAL_SPACE];// 出队位置
head++;
return resultValue;
}// Of dequeue
/**
******************
* Overrides the method claimed in Object, the superclass of any class.
******************
*/
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;
}// Of toString
/**
******************
* 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
2.运行结果:
3.注意:
a.循环队列
b.此处,head一直在增,所以必需要进行取余操作,不能直接用head