用数组实现一个队列改进版
生活随笔
收集整理的這篇文章主要介紹了
用数组实现一个队列改进版
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
package com.summer.arrayQueue;import java.util.Arrays;
import java.util.Scanner;public class ArrayQueueDemo {public static void main(String[] args) {//測試一把//創(chuàng)建一個隊列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): 添加數(shù)據(jù)到隊列");System.out.println("g(get): 從隊列取出數(shù)據(jù)");System.out.println("h(head): 查看隊列頭的數(shù)據(jù)");key = scanner.next().charAt(0);//接收一個字符switch (key) {case 's':queue.showQueue();break;case 'a':System.out.println("輸出一個數(shù)");int value = scanner.nextInt();queue.addQueue(value);break;case 'g': //取出數(shù)據(jù)try {int res = queue.getQueue();System.out.printf("取出的數(shù)據(jù)是%d\n", res);} catch (Exception e) {// TODO: handle exceptionSystem.out.println(e.getMessage());}break;case 'h': //查看隊列頭的數(shù)據(jù)try {int res = queue.headQueue();System.out.printf("隊列頭的數(shù)據(jù)是%d\n", res);} catch (Exception e) {// TODO: handle exceptionSystem.out.println(e.getMessage());}break;case 'e': //退出scanner.close();loop = false;break;default:break;}}System.out.println("程序退出~~");}}// 使用數(shù)組模擬隊列-編寫一個ArrayQueue類
class ArrayQueue {private int maxSize; // 表示數(shù)組的最大容量private int front; // 隊列頭private int rear; // 隊列尾private int[] arr; // 該數(shù)據(jù)用于存放數(shù)據(jù), 模擬隊列// 創(chuàng)建隊列的構(gòu)造器public ArrayQueue(int arrMaxSize) {maxSize = arrMaxSize;arr = new int[maxSize];front = -1; // 指向隊列頭部,分析出front是指向隊列頭的前一個位置.rear = -1; // 指向隊列尾,指向隊列尾的數(shù)據(jù)(即就是隊列最后一個數(shù)據(jù))}// 判斷隊列是否滿public boolean isFull() {return rear == maxSize - 1;}// 判斷隊列是否為空public boolean isEmpty() {return rear == front;}// 添加數(shù)據(jù)到隊列public void addQueue(int n) {// 判斷隊列是否滿if (isFull()) {System.out.println("隊列滿,不能加入數(shù)據(jù)~");return;}rear++; // 讓rear 后移arr[rear] = n;}// 獲取隊列的數(shù)據(jù), 出隊列public int getQueue() {// 判斷隊列是否空if (isEmpty()) {// 通過拋出異常throw new RuntimeException("隊列空,不能取數(shù)據(jù)");}front++; // front后移int i = arr[front];//取出后置當前位為0arr[front]=0;Boolean flag=true;//判斷數(shù)組是否都為0 如果都為0,說明隊列空了,重置隊列for (int j : arr) {if (j!=0){flag=false;}}if ((front==maxSize&&rear==maxSize)||flag){rear=-1;front=-1;//清空數(shù)組Arrays.fill(arr,0);}return i;}// 顯示隊列的所有數(shù)據(jù)public void showQueue() {// 遍歷if (isEmpty()) {System.out.println("隊列空的,沒有數(shù)據(jù)~~");return;}for (int i = 0; i < arr.length; i++) {System.out.printf("arr[%d]=%d\n", i, arr[i]);}}// 顯示隊列的頭數(shù)據(jù), 注意不是取出數(shù)據(jù)public int headQueue() {// 判斷if (isEmpty()) {throw new RuntimeException("隊列空的,沒有數(shù)據(jù)~~");}return arr[front + 1];}
}
總結(jié)
以上是生活随笔為你收集整理的用数组实现一个队列改进版的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QTcpSocket客户端和服务端发送图
- 下一篇: HDU 613 Kolakoski