C++ 中佇列的陣列實現


佇列是一種線性資料結構,其操作順序為 FIFO(先進先出)。

陣列是一種資料結構,它包含相同資料型別的元素,儲存在連續的記憶體位置中。

在佇列中,插入和刪除操作在佇列的兩端進行。與棧相比,它的實現稍微複雜一些。

在佇列的陣列實現中,我們建立一個大小為 n 的陣列佇列,並使用兩個變數 top 和 end。

現在,最初陣列為空,即 top 和 end 都位於陣列的索引 0 處。隨著元素新增到佇列 **(插入)**,end 變數的值會增加。end 的值可以增加到 n,即陣列的最大長度。

當需要從佇列中刪除元素 **(刪除)** 時,top 變數的值會增加。top 的值可以增加到 end 的值。

佇列操作的實現

**入隊** - 它是將元素新增到佇列的操作。在將元素新增到佇列之前,我們將檢查佇列是否已滿。檢查條件結束,如果小於 n,則我們可以將元素儲存在 queue[end] 中。並使 end 增加 1。

溢位條件是指陣列已滿,即 end == n。

**出隊** - 它是刪除佇列元素的操作。在刪除佇列元素之前,我們將檢查佇列是否為空。檢查佇列是否為空的條件是檢查 top 和 end 的值。如果 top == end,則陣列為空。

如果有元素,我們將出隊陣列。透過將陣列左側的所有元素向左移動一個位置。

**隊首** - 提取佇列的第一個元素,即 array[top]。此操作僅可在陣列不為空時執行。

**顯示** - 此操作顯示佇列中的所有元素。即遍歷佇列。

演算法

ENQUEUE :
Step 1 : if (end == n), print : “OVERFLOW”. Exit
Step 2 : queue[end] = data and end++
DEQUEUE :
Step 1 : If (top == 0), print : “empty Queue”. Exit
Step 2 : shift all elements one position left. End-- ;

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
struct Queue {
   int top, end, n;
   int* queue;
   Queue(int c){
      top = end = 0;
      n = c;
      queue = new int;
   }
   ~Queue() { delete[] queue;
}
void Enqueue(int data){
   if (n == end) {
      printf("\nQueue is full\n");
      return;
   }
   else {
      queue[end] = data;
      end++;
   }
   return;
}
void Dequeue(){
   if (top == end) {
      printf("\nQueue is empty\n");
      return;
   }
   else {
      for (int i = 0; i < end - 1; i++) {
         queue[i] = queue[i + 1];
      }
      end--;
   }
   return;
}
void Display(){
   int i;
   if (top == end) {
      printf("\nQueue is Empty\n");
      return;
   }
   for (i = top; i < end; i++) {
      printf(" %d <-- ", queue[i]);
   }
   return;
}
void Front(){
   if (top == end) {
      printf("\nQueue is Empty\n");
      return;
   }
   printf("\nFront Element is: %d", queue[top]);
   return;
}
};
int main(void){
   Queue q(4);
   q.Display();
   q.Enqueue(12);
   q.Enqueue(89);
   q.Enqueue(65);
   q.Enqueue(34);
   q.Display();
   q.Enqueue(92);
   q.Display();
   q.Dequeue();
   q.Dequeue();
   q.Display();
   q.Front();
   return 0;
}

輸出

Queue is Empty
12 <-- 89 <-- 65 <-- 34 <--
Queue is full
12 <-- 89 <-- 65 <-- 34 <-- 65 <-- 34 <--
Front Element is: 65

更新於: 2019-10-24

3K+ 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告