1. 程式人生 > >java數據結構----隊列,優先級隊列

java數據結構----隊列,優先級隊列

堆數據結構 比較 new n) .com ring ret 插入數據 pan

1.隊列:和棧中的情況不同,隊列中的數據項不總是從數組下標0開始,移除一個數據項後,隊頭指針會指向下標較高的數據項,其特點:先入先出

2.圖解

技術分享圖片

3.隊列的實現代碼:

  3.1.Queue.java

 1 package com.cn.queue;
 2 /**
 3  * 數據結構之隊列實現
 4  * @author Administrator
 5  *
 6  */
 7 public class Queue {
 8 private int maxsize;
 9 private long[] queuearray;
10 private int front;
11 private
int rear; 12 private int nItems; 13 public Queue(int s){ 14 maxsize = s; 15 queuearray = new long[maxsize]; 16 front = 0; 17 rear = -1; 18 nItems = 0; 19 } 20 public void insert(long j){ 21 if (rear == maxsize - 1) 22 rear = -1; 23 queuearray[++ rear] = j; 24 nItems ++;
25 } 26 public long remove(){ 27 long temp = queuearray[front ++]; 28 if (front == maxsize) 29 front = 0; 30 nItems --; 31 return temp; 32 } 33 public long peekFront(){ 34 return queuearray[front]; 35 } 36 public boolean isEmpty(){ 37 return (nItems == 0); 38 } 39 public
boolean isFull(){ 40 return (nItems == maxsize); 41 } 42 public int size(){ 43 return nItems; 44 } 45 46 }

  3.2.QueueTest.java

 1 package com.cn.queue;
 2 
 3 public class QueueTest {
 4 public static void main(String[] args) {
 5     Queue q = new Queue(100);
 6     q.insert(100);
 7     q.insert(200);
 8     q.insert(300);
 9     while (q.size()!=0){
10         System.out.print(q.remove()+"   ");
11     }
12     System.out.println("");
13     System.out.println(q.isEmpty());
14 }
15 }

4.隊列插入和刪除的時間復雜度和棧的一樣,都是O(1)

5.優先級隊列:優先級隊列是比棧和隊列更加專用的數據結構,他有一個隊頭和隊尾,並且也是從隊頭移除數據項,不過在優先級隊列中,數據項按關鍵字的值有序,這樣關鍵字最小的數據項總是在隊頭,而最大的就在隊尾。做插入操作時會按照順序插入到合適的位置以確保隊列的順序。除了可以快速訪問最小關鍵值的數據項,優先隊列還必須實現非常快的插入數據項,由此,優先級隊列通常使用一種稱為堆得數據結構實現。本程序暫時使用數組實現,該實現的插入比較慢,適用於數據量小,並且對速度要求並不高場景。

6.優先級隊列的實現:

  6.1.PriorityQ.java

 1 package com.cn.queue;
 2 /**
 3  * 優先級隊列的實現代碼
 4  * @author Administrator
 5  *
 6  */
 7 public class PriorityQ {
 8 private int maxsize;
 9 private long[] queuearray;
10 private int nItems;
11 public PriorityQ(int s){
12     maxsize = s;
13     queuearray = new long[maxsize];
14     nItems = 0;
15 }
16 public void insert(long item){
17     int k;
18     if (nItems == 0)
19         queuearray[nItems ++] = item;
20     else{
21         for(k = nItems - 1;k >= 0;k --){
22             if (item > queuearray[k])
23                 queuearray[k + 1] = queuearray[k];
24             else
25                 break;
26         }
27         queuearray[k + 1] = item;
28         nItems ++;
29     }
30 }
31 public long remove(){
32     return queuearray[-- nItems];
33 }
34 public long peekmin(){
35     return queuearray[nItems - 1];
36 }
37 public boolean isEmpty(){
38     return (nItems == 0);
39 }
40 public boolean isFull(){
41     return (nItems == maxsize);
42 }
43 }

  6.2圖解

技術分享圖片

7.優先級隊列的效率:插入操作時間復雜度位O(N),刪除操作時間復雜度為O(1),後續堆數據結構將改進他。

java數據結構----隊列,優先級隊列