数据结构 队列的简单应用的c++代码实现
时间: 2023-08-17 18:38:45 浏览: 52
下面是使用 C++ 实现队列的简单应用的代码示例:
```c++
#include <iostream>
using namespace std;
const int MAX_SIZE = 100; // 队列的最大容量
class Queue {
private:
int head; // 队头指针
int tail; // 队尾指针
int data[MAX_SIZE]; // 队列数据
public:
Queue() { // 构造函数
head = 0;
tail = 0;
}
bool isEmpty() { // 判断队列是否为空
return head == tail;
}
bool isFull() { // 判断队列是否已满
return tail == MAX_SIZE;
}
bool push(int value) { // 入队
if (isFull()) {
return false;
}
data[tail++] = value;
return true;
}
bool pop() { // 出队
if (isEmpty()) {
return false;
}
head++;
return true;
}
int front() { // 获取队头元素
if (isEmpty()) {
return -1; // 如果队列为空,返回 -1 表示不存在该元素
}
return data[head];
}
int size() { // 获取队列长度
return tail - head;
}
};
int main() {
Queue q;
q.push(1);
q.push(2);
q.push(3);
cout << "队列的长度为:" << q.size() << endl;
cout << "队头元素为:" << q.front() << endl;
q.pop();
cout << "执行出队操作后,队头元素为:" << q.front() << endl;
return 0;
}
```
该示例中,我们定义了一个 `Queue` 类,其中包含了队头指针、队尾指针和队列数据等属性,以及入队、出队、获取队头元素和判断队列是否为空或已满等方法。在 `main()` 函数中,我们创建了一个队列对象 `q`,并向其中添加了三个元素。然后,我们使用 `size()` 方法获取了队列的长度,使用 `front()` 方法获取了队头元素,并执行了一次出队操作,最后再次使用 `front()` 方法获取了队头元素。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)