一、隊列的介紹
我們在超市付款時,先排隊的總是先付款完成(排除插隊),隊列的一個特點就是“先進先出,后進后出”
特點
- 隊列是一個有序列表,可以通過數組和鏈表來實現
- 遵循”先進先出,后進后出的原則“
- 如圖在用數組表示隊列時,總是在底部插入數據,在頂部拿出數據
二、數組模擬隊列分析
MaxSize是數組的長度,那MaxSize-1就是隊列的最大下標了,front和rear是隊列前后的下標,front是取出數據時改變,rear時添加數據時改變
添加數據時:
- 首先判斷隊列是否滿,怎么判斷是否滿?
尾指針rear隨着添加數據而增加,當rear指向隊列最大下標時為滿,即rear==Maxsize
- 不滿時,尾指針rear初始值指向-1,所以添加前需要先將進行上移(即rear++),然后對rear進行賦值
取出數據時:
- 先判斷隊列是否是空?
當rear==front時(即上圖最左邊),即為空
- 不為空將尾指針front上移,即進行front++操作
三、代碼實現
java
1 private int Maxsize; 2 private int[] arr; 3 private int front; 4 private int rear; 5 //構建函數 6 public ArrayQueue(int arrMaxsize){ 7 Maxsize=arrMaxsize; 8 arr=new int[Maxsize]; 9 front=-1; 10 rear=-1; 11 } 12 //判斷數組是否時空 13 public boolean isEmpty(){ 14 return front==rear; 15 } 16 17 //判斷數組是否是滿的 18 public boolean isFull(){ 19 return rear==Maxsize-1; 20 } 21 22 //為數組添加數據 23 public void add(int n){ 24 if (isFull()){ 25 System.out.println("數組已經滿了"); 26 return; 27 } 28 rear++; 29 arr[rear]=n; 30 } 31 //刪除數組數據 32 public int remove(){ 33 if (isEmpty()){ 34 new RuntimeException("數組是空的"); 35 } 36 front++; 37 return arr[front]; 38 } 39 40 //獲取頭數據 41 public int getHeadDate(){ 42 if (isEmpty()){ 43 new RuntimeException("數組是空的"); 44 } 45 46 return arr[front+1]; 47 } 48 //顯示所有數據 49 public void allDate(){ 50 if (isEmpty()){ 51 new RuntimeException("數組是空的"); 52 } 53 for (int i=0;i<Maxsize;i++){ 54 System.out.printf("arr[%d]=%d\n",i,arr[i]); 55 } 56 57 }
四、優化
根據上面的代碼發現,數組只能使用一次,取出數據后的空位置也不能進行添加,需要引入循環隊列來解決問題
預留一個位置判斷隊列是否滿:
當取出一個后發現隊列沒滿,可以繼續添加:
代碼實現
1 private int Maxsize; 2 private int arr[]; 3 private int front;//默認是0 4 private int rear;//默認是0 5 6 //構建函數 7 public CircleArray(int arrMaxsize){ 8 Maxsize=arrMaxsize; 9 arr=new int[Maxsize]; 10 } 11 //判斷數組是否時空 12 public boolean isEmpty(){ 13 return rear==front; 14 } 15 16 //判斷數組是否是滿的 17 public boolean isFull(){ 18 return (rear+1)%Maxsize==front; 19 } 20 21 //為數組添加數據 22 public void add(int n){ 23 if (isFull()){ 24 System.out.println("數組已經滿了"); 25 return; 26 } 27 arr[rear]=n; 28 rear=(rear+1)%Maxsize; 29 } 30 //刪除數組數據 31 public int remove(){ 32 if (isEmpty()){ 33 new RuntimeException("數組是空的"); 34 } 35 //先把數據值給一個局部變量 36 int a=arr[front]; 37 front=(front+1)%Maxsize; 38 return a; 39 } 40 41 //獲取頭數據 42 public int getHeadDate(){ 43 if (isEmpty()){ 44 new RuntimeException("數組是空的"); 45 } 46 47 return arr[front]; 48 } 49 //顯示所有數據 50 public void allDate(){ 51 if (isEmpty()){ 52 new RuntimeException("數組是空的"); 53 } 54 55 for (int i=front;i<front+size();i++){ 56 System.out.printf("arr[%d]=%d\n",i%Maxsize,arr[i%Maxsize]); 57 } 58 59 } 60 61 //有效數據長度,(Maxsize-front+rear)%Maxsize 當rear<front時,長度是(maxsize-front)+(rear-0) 62 public int size(){ 63 if (isEmpty()){ 64 return 0; 65 } 66 return (Maxsize-front+rear)%Maxsize; 67 }