JAVA数据结构与算法【队列、数组模拟(环形)队列】
生活随笔
收集整理的這篇文章主要介紹了
JAVA数据结构与算法【队列、数组模拟(环形)队列】
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
隊列
使用場景:排隊
隊列介紹
- 隊列是一個有序列表,可以用數組或是鏈表來實現。
- 遵循先入先出的原則。即:先存入隊列的數據,要先取出。后存入的要后取出
- 示意圖:(使用數組模擬隊列示意圖)
數組模擬隊列
- 隊列本身是有序列表,若使用數組的結構來存儲隊列的數據,則隊列數組的聲明如下圖, 其中 maxSize 是該隊列的最大容量。
- 因為隊列的輸出、輸入是分別從前后端來處理,因此需要兩個變量 front及 rear分別記錄隊列前后端的下標,front 會隨著數據輸出而改變,而 rear則是隨著數據輸入而改變,如圖所示:
數組模擬隊列
當我們將數據存入隊列時稱為”addQueue”,addQueue 的處理需要有兩個步驟:思路分析
代碼實現
package com.henu.queue;import java.util.Scanner;/*** @author George* @description**/ public class ArrayQueueDemo {public static void main(String[] args) {//測試//創建一個隊列ArrayQueue queue = new ArrayQueue(3);char key;//接收用戶輸入Scanner scanner = new Scanner(System.in);boolean loop = true;while(loop){System.out.println("s(show):顯示隊列");System.out.println("e(exit):退出程序");System.out.println("a(add):添加數據");System.out.println("g(get):從隊列取出數據");System.out.println("h(head):查看隊列頭的數據");key = scanner.next().charAt(0);//接收一個字符switch (key){case 's':queue.showQueue();break;case 'a':System.out.println("輸入一個數");int value = scanner.nextInt();queue.addQueue(value);break;case 'g':try{int res = queue.getQueue();System.out.printf("取出的數據是%d\n",res);}catch (Exception e){System.out.println(e.getMessage());}break;case 'h':try {int res = queue.headQueue();System.out.printf("隊列頭的數據是%d\n",res);} catch (Exception e) {System.out.println(e.getMessage());}break;case 'e':scanner.close();loop = false;break;default:break;}}} }//使用數組模擬隊列-編寫一個ArrayQueue類 class ArrayQueue{private int maxSize;//表示數組的最大容量private int front;//隊列頭private int rear;//隊列尾private int[] arr;//該數據用于存放數據,模擬隊列//創建隊列的構造器public ArrayQueue(int arrMaxSize){maxSize = arrMaxSize;arr = new int[maxSize];front = -1;//指向隊列頭部,分析出front是指向隊列頭的前一個位置rear = -1;//指向隊列尾,指向隊列尾的數據(即就是隊列的最后一個數據)}//判斷隊列是否滿public boolean isFull(){return rear == maxSize-1;}//判斷隊列是否為空public boolean isEmpty(){return rear == front;}//添加數據到隊列public void addQueue(int n){if (isFull()) {System.out.println("隊列滿,不能加入數據~");return;}rear++;//讓rear后移arr[rear] = n;}//獲取隊列的數據,出隊列public int getQueue(){//判斷隊列是否為空if (isEmpty()) {//拋出異常throw new RuntimeException("隊列空,不能取出數據");}front++;//front后移return arr[front];}//顯示隊列的所有數據public void showQueue(){//遍歷if (isEmpty()) {System.out.println("隊列空的,沒有數據~");return;}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];}}具體測試結果就不展示了,不過這樣寫有它的缺陷。【可以自己測試測試】
問題發現并分析:
?
總結
以上是生活随笔為你收集整理的JAVA数据结构与算法【队列、数组模拟(环形)队列】的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql的分页查询
- 下一篇: 大剑无锋之简单说一下聚簇索引和非聚簇索引