循环顺序队列

循环队列 相比 一般队列 可以避免 数据移动,这个效率就会高很多了

循环队列的关键:确定好队空和队满的判定条件  

 1 public class CircularQueue {
 2   // 数组:items,数组大小:n
 3   private String[] items;
 4   private int n = 0;
 5   // head 表示队头下标,tail 表示队尾下标
 6   private int head = 0;
 7   private int tail = 0;
 8 
 9   // 申请一个大小为 capacity 的数组
10   public CircularQueue(int capacity) {
11     items = new String[capacity];
12     n = capacity;
13   }
14 
15   // 入队
16   public boolean enqueue(String item) {
17     // 队列满了
18     if ((tail + 1) % n == head) return false;
19     items[tail] = item;
20     tail = (tail + 1) % n;
21     return true;
22   }
23 
24   // 出队
25   public String dequeue() {
26     // 如果 head == tail 表示队列为空
27     if (head == tail) return null;
28     String ret = items[head];
29     head = (head + 1) % n;
30     return ret;
31   }
32 }

 

posted @ 2019-05-24 13:53  TeemoHQ  阅读(148)  评论(0)    收藏  举报