1. 程式人生 > 實用技巧 >資料結構與演算法 -- 程式篇 -- 模擬佇列程式

資料結構與演算法 -- 程式篇 -- 模擬佇列程式

package com.lfw.queue;

import java.util.Scanner;

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){ //TODO:handle exception System.out.println(e.getMessage()); } break; case 'h': //檢視佇列頭的資料 try{ int res = queue.headQueue(); System.out.printf("佇列頭的資料是%d\n"); }catch (Exception e){ //TODO;handle exception System.out.println(e.getMessage()); } break; case 'e'://退出 scanner.close(); loop = false; break; default: break; } } System.out.println("程式退出~~"); } } // 使用陣列模擬佇列-編寫一個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]; } }