日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

数组模拟队列(代码实现)

發布時間:2025/3/19 编程问答 9 豆豆
生活随笔 收集整理的這篇文章主要介紹了 数组模拟队列(代码实现) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

數據結構可分為兩種,第一種是線性結構,第二種是非線性結構,線性結構又分為連續存儲和鏈表存儲。
常見的線性結構有數組,鏈表,隊列,棧;
以下是數組模擬隊列的實現(隊列特點就是先進先出):

//數組模擬隊列 public class ArrayQueueDemo {public static void main(String[] args) {ArrayQueue queue = new ArrayQueue(3);char key = ' '; //接收用戶輸入Scanner scanner = new Scanner(System.in);boolean f = true;while(f){System.out.println("s:顯示隊列");System.out.println("a:添加數據");System.out.println("e:退出程序");System.out.println("h:顯示頭部數據");System.out.println("g:取出數據");key = scanner.next().charAt(0);switch(key) {case 's':queue.show();break;case 'a':System.out.println("輕輸入一個數據");int value = scanner.nextInt();queue.add(value);break;case 'h':try {int res = queue.head();System.out.println(res);} catch (Exception e) {// TODO: handle exceptionSystem.out.println(e.getMessage());}break;case 'g':try {int res = queue.get();;System.out.println(res);} catch (Exception e) {// TODO: handle exceptionSystem.out.println(e.getMessage());}break;case 'e':scanner.close();f = false;break;default:break;}}System.out.println("退出程序");}}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; //隊列頭部 指向的是頭部前面的位置rear = -1;// 隊列尾部 包含尾部數據}//判斷隊列是否滿了public boolean isFull() {return rear == maxSize - 1;}//判斷隊列是否為空public boolean isNull() {return front == rear;}//將數據添加到隊列中public void add(int num ) {if(isFull()) {System.out.println("隊列已經滿了,不能添加數據");return;}rear ++;arr[rear] = num;}//取出隊列數據 相當于刪除數據public int get() {if(isNull()) {throw new RuntimeException("隊列為空,沒有數據");}front++;return arr[front];}//顯示隊列的全部數據public void show() {if(isNull()) {System.out.println("隊列為空,沒有數據");return;}for(int i = 0; i<arr.length;i++) {System.out.println(arr[i]);}}//顯示隊列頭部數據public int head() {if(isNull()) {throw new RuntimeException("隊列為空");}return arr[front+1];}}

總結

以上是生活随笔為你收集整理的数组模拟队列(代码实现)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。