日撸 Java 三百行学习笔记day18

第 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[],再移动。

 

在删除元素时:,这是从队列的头部进行操作,头指针就是指向当前元素。

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值