關注 “弋凡”(YiFan)微信公衆號吧 記錄簡單筆記 做你的最愛
隊列
隊列是一個有序列表,可以使用數組或者鏈表實現
遵循先入先出的原則。 即先存入列表的數據要先取出,後存入的要後取出。
使用數組模擬隊列如圖:
思路分析:
front指向隊列的頭部,rear指向隊列的尾部。
當有數據輸入時,隊列的頭部不動,尾部向上移,
當rear = maxSize - 1 時,隊列滿,無法再加入數據;
當有數據取出時,隊列的尾部不動,頭部上移,也就是取出先加入的數據,再取出後加入的數據,
當 rear = front 時,隊列空,此時無法再取出數據。用數組模擬隊列時front 和 rear 均初始化爲-1。front 爲-1指向隊列頭部就是隊列頭數據的前一個數據,rear 爲-1指向隊列尾部就是隊列的最後一個數據
代碼實現
package com.yifan.linear;
import java.util.Scanner;
/**
* @Author YIFan
* @Date 2020/6/10 12:15
* @Version 1.0
*/
public class ArrayQueue {
public static void main(String[] args) {
ArrayQueeTest quee = new ArrayQueeTest(4);
Scanner scanner = new Scanner(System.in);
boolean loop = true;
while (loop){
System.err.println("(s) 顯示隊列信息");
System.err.println("(a) 添加數據到隊列");
System.err.println("(g) 從隊列取出數據");
System.err.println("(h) 顯示隊列頭數據");
System.err.println("(e) 退出程序");
char key = scanner.next().charAt(0);
switch (key){
case 'e':
loop = false;
break;
case 's':
try {
quee.showQueue();
} catch (Exception e) {
System.err.println(e.getMessage());
}
break;
case 'a':
try {
System.out.println("請輸入一個數據添加到隊列");
int i = scanner.nextInt();
quee.addQueue(i);
} catch (Exception e) {
System.err.println(e.getMessage());
}
break;
case 'g':
try {
System.out.println("取出:"+quee.getQueue());
} catch (Exception e) {
System.err.println(e.getMessage());
}
break;
case 'h':
try {
System.out.println("頭數據:"+quee.headQueue());
} catch (Exception e) {
System.err.println(e.getMessage());
}
break;
}
}
}
}
// 使用數組模擬隊列
class ArrayQueeTest{
private int maxSize;//數組的最大容量
private int front;//隊列頭
private int rear;//隊列尾
private int[] arr;//數組用於存放數據 ,模擬隊列
//創建隊列的構造器
public ArrayQueeTest(int maxSize){
this.maxSize = maxSize;
arr = new int[maxSize];
front = -1;// 指向隊列頭部 就是 隊列頭數據的前一個數據
rear = -1;// 隊列尾部 就是 隊列的最後一個數據
}
// 判斷隊列是否滿
public boolean isFull(){
return rear == maxSize-1;
}
// 判斷隊列是否爲null
public boolean isEmpty(){
return rear == front;
}
// 添加數據到隊列, 進隊列
public void addQueue(int num){
if(isFull()){
throw new RuntimeException("隊列已滿,加入不了");
}
rear++;//讓 rear 後移
arr[rear] = num;
}
// 獲取隊列的數據 ,出隊列
public int getQueue(){
if (isEmpty()){
throw new RuntimeException("隊列爲空,不能取值");
}
front++;// front 後移
return arr[front];
}
// 顯示隊列數據
public void showQueue(){
if (isEmpty()){
throw new RuntimeException("隊列爲空,沒有數據");
}
for (int i = 0; i < arr.length; i++) {
System.out.printf("arr[%d]=%d\n",i,arr[i]);
}
}
// 顯示隊列頭數據
public int headQueue(){
if (isEmpty()){
throw new RuntimeException("隊列爲空,沒有數據");
}
return arr[front+1];
}
}