Programming Practice

使用 C++ 程式語言,將原有的佇列 (queue) C 語言程式改寫為 Queue 的類別 (class) 程式。使用雙向連結表 (double-linked list) 實作一個佇列。佇列的主要運算如下:

  1. Queue(): 建構函式,產生一個空的佇列,

  2. ~Queue():解構函式,須將佇列中的剩餘節點釋放。

  3. void enqueue(int):將某個值的節點放入佇列的尾部 (tail),

  4. void dequeue():將佇列頭部 (head) 的節點移出,並回傳該節點的值,

  5. int first():回傳頭部節點的值,

  6. ostream &operator<<(ostream&, const Queue&):友函式,從頭部至尾部輸出佇列中所有節點的值。

在主程式中宣告一個佇列類別的物件變數,然後寫一個無限迴圈 (infinite loop),選擇並執行下列的指令:

  1. 讀入一個正整數,將此正整數的值放入佇列,

  2. 移出一個佇列的節點,並印出該節點的值

  3. 列印佇列頭部節點的值

  4. 從頭部至尾部列印佇列中所有節點的值

  5. 終止程式執行。

以下為程式執行範例:

****************************************

1. Enqueue an element to the queue
2. Dequeue an element from the queue
3. Print head of queue
4. Print queue elements
5. Exit the program

Input command:
1

Input the element being enqueued:
10

****************************************

1. Enqueue an element to the queue
2. Dequeue an element from the queue
3. Print head of queue
4. Print queue elements
5. Exit the program

Input command:
1

Input the element being enqueued:
20

****************************************

1. Enqueue an element to the queue
2. Dequeue an element from the queue
3. Print head of queue
4. Print queue elements
5. Exit the program

Input command:
1

Input the element being enqueued:
30

****************************************

1. Enqueue an element to the queue
2. Dequeue an element from the queue
3. Print head of queue
4. Print queue elements
5. Exit the program

Input command:
3

The head element is of value: 10

****************************************

1. Enqueue an element to the queue
2. Dequeue an element from the queue
3. Print head of queue
4. Print queue elements
5. Exit the program

Input command:
4

The queue elements are (from head to tail):
  10   20   30

****************************************

1. Enqueue an element to the queue
2. Dequeue an element from the queue
3. Print head of queue
4. Print queue elements
5. Exit the program

Input command:
2

The dequeued element: 10

****************************************

1. Enqueue an element to the queue
2. Dequeue an element from the queue
3. Print head of queue
4. Print queue elements
5. Exit the program

Input command:
4

The queue elements are (from head to tail):
  20   30

****************************************

1. Enqueue an element to the queue
2. Dequeue an element from the queue
3. Print head of queue
4. Print queue elements
5. Exit the program

Input command:
5