循环数组实现队列以及算法分析

 1 /*
 2 *   使用数组实现循环队列
 3 */
 4 public class ArrarImplyQueue {
 5     //底层数组
 6     private Object[] arr;
 7     //用于指向队列头部
 8     private int front;
 9     //用于指向队列尾部
10     private int tail;
11 
12     //数组的默认大小为10
13     public ArrarImplyQueue(){
14         this(10);
15     }
16 
17     //使用自定义大小
18     public ArrarImplyQueue(int size){
19         arr = new Object[size];
20         front = 0;
21         tail = 0;
22     }
23 
24     // 判断是否满队列
25     public boolean isFull(){
26         return (tail+1)%arr.length == front;
27     }
28 
29     //进入队列
30     public boolean add(Object obj){
31       //当队列的对头索引值和队尾索引值相等时返回false
32         if(isFull()){
33             return false;
34         }
35         arr[tail] = obj;
36         //如果下标索引超出数组的长度则从数组的起始位置重新开始
37         tail = (tail+1)%arr.length;
38         return true;
39     }
40 
41     //出队列
42     public Object remove(){
43       //如果下标索引超出数组的长度则返回null 
44       if (front == tail){
45             return null;
46         }
47         //即将出队列的值保存到临时变量obj中
48         Object obj =  arr[front];
49         //数据出队列将下标索引值移动
50         front = (front+1)%arr.length;
51         return obj;
52     }
53 
54     public static void main(String[] args) {
55         ArrarImplyQueue queue = new ArrarImplyQueue();
56         queue.add("第一");
57         queue.add("第二");
58         System.out.println(queue.remove());
59         System.out.println(queue.remove());
60     }
61 }
62     
 

  不成熟小想法:对满队列判断公式 (tail+1)%arr.length == front; 的说明

情况分析:
一、当尾元素在后,头元素在前,且满队列时,只有tail=9,front=0一种情况,公式(9+1)%10 == 0,成立。
  这种情况可以用通用算法:tail+1-front==arr.length,
  即(tail+1)-arr.length==front,front必然为0
  -》(tail+1)-arr.length=0
  -》(tail+1)=arr.length
  -》(tail+1)%arr.length == 0

二、当尾元素在前,头元素在后,且满队列时,有多种情况,例如tail=4,front=5时,公式(4+1)%10 == 5,成立。
  这种情况,因为(tail+1)必然小于arr.length,因此取模结果必然等于(tail+1)自身,所以不做取模操作也成立。
将以上两种情况进行算法统一,即: (tail+1)%arr.length == front;

猜你喜欢

转载自www.cnblogs.com/cowshed/p/12375513.html