数据结构 队列的基本操作

数据结构 队列的基本操作

队列是不同数据类型的集合,是数据结构的一个重要组成部分,遵循特定的顺序插入和删除元素。在本教程中,我们将了解队列的基本操作。

什么是数据结构中的队列

队列是一种线性数据结构,类似于现实生活中的队列。你们都曾在学校、计费柜台或任何其他地方参加过一些队列,在队列中,先进入的人将先退出。同样,数据结构中的队列也遵循先进先出原则,即定义为先进先出。在队列中首先插入的元素将首先终止,与其余的相比。

一个队列有两个端点,并向两端开放。

  • 前端– 它是元素从队列中移出的一端。

  • 后端– 它是元素被插入队列的一端。

数据结构中队列的基本操作

它可以用一维数组、指针、结构和链接列表来实现。C++库包含各种帮助管理队列的内置函数,其操作只发生在前端和后端。

声明一个队列的语法

queue<data type> queue_name
Bash

例子

queue<int> q
queue<string> s
Bash

基本队列操作

在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;
}
Bash

输出

Elements of the queue are: 451
Bash

在上面的例子中,我们创建了一个队列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;
}
Bash

输出

size of queue is : 451
Bash

队列的 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;
}
Bash

输出

No queue has elements
Bash

结论

一个队列可以存储整数和字符串元素。在数据结构中,还有一个队列叫做优先级队列,它在所有队列元素中具有优先权。

我希望本教程能帮助你理解数据结构中队列的含义。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册