栈与队列 - 队列
队列:先进先出
在现实中,买电影票排队,当前面的的人买完票离开之后,后面的人都要往前移动一步。在计算机中也可以这么类似的做法,但是效率很低。所以,我们用了队列中的队头(front)和队尾(rear)指针保持所有的数据项不变。
循环队列:在往队列中插入一个新的数据项,rear箭头往上移动,移向数组下标大的位置。移除数据项时,front也需要往上移动一步。当插入了更多的数据项时,rear已经在最大的坐标位置了,再插入的话队尾rear需要回绕到队头front指针下面。可以想象成一个队头和队尾连接的队列,当数据项nItems已经充满了整个队列,rear和front会重合一起。
1 public class Queue { 2 3 private int maxSize ; 4 private int[] queueArray; 5 private int front; //队头 6 private int rear; //队尾 7 private int nItems; //当前数据项的个数 8 9 public Queue(int m){ 10 this.maxSize = m; 11 queueArray = new int[maxSize]; 12 front = 0; 13 rear = -1; 14 nItems = 0; 15 } 16 17 public void insert(int data){ 18 if(rear == maxSize-1){ 19 rear = -1; 20 } 21 queueArray[++rear] = data; 22 nItems ++; 23 } 24 25 public int remove(){ 26 int temp = queueArray[front++]; 27 if(front == maxSize){ 28 front = 0; 29 } 30 nItems --; 31 return temp; 32 } 33 34 public int peekFront(){ 35 return queueArray[front]; 36 } 37 38 public boolean isEmpty(){ 39 return nItems == 0; 40 } 41 42 public boolean isFull(){ 43 return nItems == maxSize; 44 } 45 46 public int size(){ 47 return nItems; 48 } 49 50 }
队列的效率:
和栈一样,队列中插入和移除数据项的时间复杂度都是O(1)。
优先级队列:数据项按关键字的值有序,最小(大)的数据项总在队头。不像队列那样必须有front、rear,它的front总是nItems-1,rear永远都是0。
1 public class PriorityQueue { 2 3 private int maxSize; 4 private int[] queueArray; 5 private int nItems; 6 7 public PriorityQueue(int s) { 8 maxSize = s; 9 queueArray = new int[maxSize]; 10 nItems = 0; 11 } 12 13 public void insert(int data){ 14 if(nItems == 0){ 15 queueArray[nItems++] = data; 16 }else{ 17 int j; 18 for(j = nItems -1; j >=0 ; j--){ 19 if(data > queueArray[j]){ 20 queueArray[j+1] = queueArray[j]; 21 }else{ 22 break; 23 } 24 } 25 queueArray[j+1]= data; 26 nItems ++; 27 } 28 } 29 30 public int remove(){ 31 return queueArray[--nItems]; 32 } 33 34 public int peekMin(){ 35 return queueArray[nItems -1]; 36 } 37 38 public boolean isEmpty(){ 39 return nItems == 0; 40 } 41 42 public boolean isFull(){ 43 return nItems == maxSize; 44 } 45 46 }
1 public static void main(String[] args) { 2 PriorityQueue qp = new PriorityQueue(10); 3 qp.insert(6); 4 qp.insert(90); 5 qp.insert(78); 6 qp.insert(1); 7 8 while(!qp.isEmpty()){ 9 System.out.println(qp.remove()); 10 } 11 12 }
打印结果:
1
6
78
90
优先级队列效率:插入操作需要O(N)的时间,而删除操作则需要O(1)的时间。