- 任務
主要是在上一篇數組模擬隊列的基礎上做了修改
數組模擬隊列移步:java學習——數組模擬隊列
- 修改了兩個重要變量front和rear所代表的位置含義
變量 | 含義 |
---|---|
front | 指向隊列第一個數據 |
rear | 指向隊列最後一個數據的後一個位置 (以區別隊列空與滿) |
- 要達到循環利用的目的,採用取模的方法:
隊列滿:(rear+1)%maxSize=front
隊列空:rear=front
隊列中有效數據個數:(rear-front+maxSize)%maxSize
- 代碼
環形隊列代碼仍然包含下列4個功能: - 加入數據到隊列
- 從隊列中取出數據
- 顯示隊列中的數據
- 顯示隊列的頭數據
如下附上代碼:
/*
*文件名稱:CircleQueue.java
*作者:陳happy
*完成日期:2020.2.5
*
*代碼功能:環形隊列(出/入隊列、顯示隊列、顯示隊頭)
*/
import java.util.Scanner;
public class CirckeQueue {
public static void main (String args[]) {
Queue queue=new Queue(4);
char key=' ';
boolean loop=true;
Scanner t=new Scanner(System.in);
while(loop) {
System.out.println("a(addQueue):入隊列");
System.out.println("o(outQueue):出隊列");
System.out.println("s(show):顯示隊列");
System.out.println("h(head):顯示隊頭");
System.out.println("e(exit):退出");
key=t.next().charAt(0);
switch(key) {
case'a':
System.out.println("請輸入要插入的數字");
int m=t.nextInt();
queue.addQueue(m);
break;
case'o':
try {
int data=queue.outQueue();
System.out.println(data);
}
catch(Exception e){
System.out.println(e.getMessage());
}
break;
case 's':
try {
queue.showQueue();
}
catch(Exception e){
System.out.println(e.getMessage());
}
break;
case'h':
try {
int ret=queue.showHead();
System.out.println(ret);
}
catch(Exception e) {
System.out.println(e.getMessage());
}
break;
case'e':
t.close();
loop=false;
break;
default:
break;
}
}
}
}
//環形隊列
class Queue {
private int maxSize;
private int front;
private int rear;
private int []arr;
//構造隊列
public Queue(int n) {
maxSize=n;
arr=new int[maxSize];
front=0;//指向隊列的第一個數據
rear=0;//指向隊列最後一個數據的後一個位置,以空出一個空間
}
//判斷隊列是否滿
public boolean isFull() {
return (rear+1)%maxSize==front;
}
//判斷隊列是否空
public boolean isEmpty() {
return rear==front;
}
//數據入隊列
public void addQueue(int m) {
//先判斷隊列是否滿
if(isFull()) {
System.out.println("隊列已經滿啦,不能添加了");
return;
}
else {
arr[rear]=m;
rear=(rear+1)%maxSize;
}
}
//數據出隊列
public int outQueue() {
if(isEmpty()) {
throw new RuntimeException("隊列空,無數據");
}
else {
int value=arr[front];
front=(front+1)%maxSize;
return value;
}
}
//顯示隊列所有數據
public void showQueue() {
if(isEmpty()) {
throw new RuntimeException("隊列空,無數據");
}
else {
for(int i=front;i<front+leng();i++) {
System.out.printf("arr[%d]=%d\n",i%maxSize,arr[i%maxSize]);
}
}
}
public int leng() {
return (rear-front+maxSize)%maxSize;
}
//顯示隊列的頭數據
public int showHead() {
if(isEmpty()) {
throw new RuntimeException("隊列空,無數據");
}
else {
return arr[front];
}
}
}
- 心得與體會
- 利用取模達到環形隊列的目的,在修改時有很多地方需要注意,在出入隊列時rear和front不能單純的++,而要注意取模;
- 遇到困難是多思考,羅列要解決的問題,學會分解問題與解決問題,加油!