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

PHPz
PHPz 转载
2023-09-17 08:53:01 873浏览

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

数据结构中的队列是什么?

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

队列有两个端点,并且对两端开放。

  • Front - 这是元素移出队列的末尾。

  • - 这是元素插入队列的末尾。

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

可以使用一维数组、指针、结构体和链表来实现。 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()函数将从最前端删除队列元素。 p>

示例

#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

结论

队列可以存储整数和字符串元素。在数据结构中,多了一个队列,称为优先队列,它对所有队列元素具有优先权。

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

以上就是数据结构中队列的基本操作的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除