代码来自闵老师”日撸 Java 三百行(11-20天)“,链接:https://blog.csdn.net/minfanphd/article/details/116974461
package datastructure.queue;
/**
*
* Circle int queue.
*
* @author WX873
*
*/
public class CircleIntQueue {
/**
* The data
*/
int[] data;
/**
* The total space. One space can never be used.
*/
public static final int TOTAL_SPACE = 10;
/**
* 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 CircleIntQueue() {
// TODO Auto-generated constructor stub
data = new int[TOTAL_SPACE];
head = 0;
tail = 0;
}//of the first constructor
/**
* Enqueue
*
* @param paraValue The given value.
*/
public void enqueue(int 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 int dequeue() {
if (tail == head) {
System.out.println("No element in the queue!");
return -1;
}//of if
int tempValue = data[head % TOTAL_SPACE];
head++;
return tempValue;
}//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[]) {
CircleIntQueue tempQueue = new CircleIntQueue();
System.out.println("Initialized, the list is: " + tempQueue.toString());
for (int i = 0; i < 5; i++) {
tempQueue.enqueue(i + 1);
}//of for i
System.out.println("Enqueue, the queue is: " + tempQueue.toString());
int tempValue = tempQueue.dequeue();
System.out.println("Dequeue, the queue is: " + tempQueue.toString());
for (int i = 0; i < 7; i++) {
tempQueue.enqueue(i + 10);
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
}//of main
}//of CircleIntQueue
今天的内容整除的用法很重要。在今天代码中,enqueue方法中的if块里用到了return。当时在想为啥void类型的方法还有返回,网上搜了一下,return有两个作用:1、返回方法指定类型的值,也可以是对象;2、结束方法,终止“return;”后面代码的执行。这样也就明白了,其实if语句里用了return,和if-else语句块的作用是一样的。
还有下图中的红色框出部分,return -1。刚开始没搞明白,如果队列中有-1,那么这两个-1是如何区分的呢?后来想明白了,return -1只是随便给一个返回值,作用是终止后面的代码运行,和后面的return tempValue不冲突。随后自己将return -1分别改称return 0和return 10进行了测试,果然如此。

本文介绍了一个基于Java实现的循环整数队列,并详细解释了队列的主要操作,包括入队、出队以及队列状态检查等核心功能。通过具体实例展示了循环队列的工作原理及其优势。
187

被折叠的 条评论
为什么被折叠?



