1. 程式人生 > >數據結構-隊列(1)

數據結構-隊列(1)

情況下 應該 解決方案 alt color spa 隊列 vat load

先入先出的數據結構

技術分享圖片

在 FIFO 數據結構中,將首先處理添加到隊列中的第一個元素

如上圖所示,隊列是典型的 FIFO 數據結構。插入(insert)操作也稱作入隊(enqueue),新元素始終被添加在隊列的末尾。 刪除(delete)操作也被稱為出隊(dequeue)。 你只能移除第一個元素

示例 - 隊列


1. 入隊:您可以單擊下面的 Enqueue 以查看如何將新元素 6 添加到隊列中。

技術分享圖片

2. 出隊:您可以單擊下面的 Dequeue 以查看將刪除哪個元素。

技術分享圖片

隊列 - 實現

為了實現隊列,我們可以使用動態數組和指向隊列頭部的索引。

如上所述,隊列應支持兩種操作:入隊和出隊。入隊會向隊列追加一個新元素,而出隊會刪除第一個元素。 所以我們需要一個索引來指出起點。

這是一個供你參考的實現:

 1 package queue;
 2 
 3 import java.util.ArrayList;
 4 import java.util.List;
 5 
 6 //"static void main" must be defined in a public class.
 7 //“靜態void main”必須在公共類中定義。
 8 class MyQueue {
 9     // store elements
10     // 存儲元素
11 private List<Integer> data; 12 // a pointer to indicate the start position 13 //指示開始位置的指針 14 private int p_start; 15 16 public MyQueue() { 17 data = new ArrayList<Integer>(); 18 p_start = 0; 19 } 20 21 /** 22 * Insert an element into the queue. Return true if the operation is successful.
23 */ 24 //在隊列中插入一個元素。如果操作成功,返回true。 25 public boolean enQueue(int x) { 26 data.add(x); 27 return true; 28 }; 29 30 /** 31 * Delete an element from the queue. Return true if the operation is successful. 32 */ 33 //從隊列中刪除一個元素。如果操作成功,返回true。 34 public boolean deQueue() { 35 if (isEmpty() == true) { 36 return false; 37 } 38 p_start++; 39 return true; 40 } 41 42 /** Get the front item from the queue. */ 43 //從隊列中獲取前面的項。 44 public int Front() { 45 return data.get(p_start); 46 } 47 48 /** Checks whether the queue is empty or not. */ 49 //檢查隊列是否為空。 50 public boolean isEmpty() { 51 return p_start >= data.size(); 52 } 53 }; 54 55 public class Main { 56 public static void main(String[] args) { 57 MyQueue q = new MyQueue(); 58 q.enQueue(5); 59 q.enQueue(3); 60 if (q.isEmpty() == false) { 61 System.out.println(q.Front()); 62 } 63 q.deQueue(); 64 if (q.isEmpty() == false) { 65 System.out.println(q.Front()); 66 } 67 q.deQueue(); 68 if (q.isEmpty() == false) { 69 System.out.println(q.Front()); 70 } 71 } 72 }

缺點


上面的實現很簡單,但在某些情況下效率很低。 隨著起始指針的移動,浪費了越來越多的空間。 當我們有空間限制時,這將是難以接受的。

技術分享圖片

讓我們考慮一種情況,即我們只能分配一個最大長度為 5 的數組。當我們只添加少於 5 個元素時,我們的解決方案很有效。 例如,如果我們只調用入隊函數四次後還想要將元素 10 入隊,那麽我們可以成功。

但是我們不能接受更多的入隊請求,這是合理的,因為現在隊列已經滿了。但是如果我們將一個元素出隊呢?

技術分享圖片
實際上,在這種情況下,我們應該能夠再接受一個元素。

數據結構-隊列(1)