資料結構中佇列的基本操作


佇列是一種包含不同資料型別的集合,是資料結構的重要組成部分,遵循特定的順序插入和刪除元素。在本教程中,我們將瞭解佇列的基本操作。

什麼是資料結構中的佇列?

佇列是一種線性資料結構,類似於現實生活中的佇列。大家在學校、收銀臺或其他任何地方都排過隊,先進入佇列的人先離開佇列。類似地,資料結構中的佇列也遵循FIFO原則,即先進先出。與其餘元素相比,最先插入佇列的元素將最先被移除。

佇列有兩個端點,並且兩端都開放。

  • 前端 − 元素從佇列中移出的端點。

  • 後端 − 元素插入佇列的端點。

它可以使用一維陣列、指標、結構體和連結串列來實現。C++庫包含各種內建函式,有助於管理佇列,其操作僅發生在前端和後端。

宣告佇列的語法

queue<data type> queue_name

示例

queue<int> q
queue<string> s

佇列的基本操作

C++中佇列最常用的操作如下:

  • pop() − 刪除佇列中的第一個元素。語法 −queue_name.pop();

  • push() −(): 用於在佇列的起始端或後端插入元素。語法 −queue_name.push(data_value);

  • front() −(): 檢查或返回佇列中第一個元素。語法 −queue_name.front();

  • size() − 獲取佇列的大小。語法 −queue_name.size();

  • empty() − 檢查佇列是否為空。根據條件返回布林值。語法 −queue_name.empty();

push() 函式的程式碼。

#include <iostream>
#include<queue>

using namespace std;

int main() {
   queue<int> q; //initializing queue
   q.push(4); //inserting elements into the queue using push() method
   q.push(5);
   q.push(1);
   cout<<"Elements of the Queue are: ";
   
   while(!q.empty()) {
      cout<<q.front()<<"";  // printing 1st element of the queue 
      q.pop();  // removing elements from the queue 
   }
   return 0;
}

輸出

Elements of the queue are: 451

在上面的示例中,我們建立了一個佇列q,並使用push()函式向其中插入元素,該函式將所有元素插入到後端。

使用empty()函式檢查佇列是否為空,如果不為空,佇列將返回第一個元素,而使用pop()函式將從前端刪除佇列元素。

示例

#include <iostream>
#include<queue>

using namespace std;

int main() {
   queue<int> q; //initializing queue
   q.push(4); //inserting elements into the queue using push() method
   q.push(5);
   q.push(1);
   cout<<"Elements of the Queue are: ";
   
   while(!q.empty()) {
      cout<<q.front()<<""; // printing 1st element of the queue 
      q.pop(); // removing elements from the queue 
   }
   return 0;
}

輸出

size of queue is : 451

佇列的empty()函式示例。

#include <iostream>
#include<queue>

using namespace std;

int main() { 
   queue<string> q; //declaring string type of queue
   q.push("cpp"); //inserting elements into the queue using push() method
   q.push("Java");
   q.push("C++");
   
   if(q.empty()) //using empty() function to return the condition
      cout<<"yes, Queue is empty";
   else
      cout<<"No, queue has elements";
   
   return 0;
}

輸出

No queue has elements

結論

佇列可以儲存整數和字串元素。在資料結構中,還有一個稱為優先佇列的佇列,它對所有佇列元素具有優先順序。

我希望本教程能幫助您理解資料結構中佇列的含義。

更新於:2023年2月22日

706 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

開始
廣告