讲解讲解c++的队列用法
时间: 2023-09-04 15:08:17 浏览: 38
C语言中的队列是一种数据结构,它是一种先进先出(FIFO)的数据结构,也就是说,先进入队列的元素先被取出,后进入队列的元素后被取出。
C语言中的队列可以使用数组或链表来实现。使用数组实现队列的基本操作包括入队操作和出队操作,入队操作将元素插入到队列的末尾,出队操作将队列的第一个元素取出并删除它。
以下是使用数组实现队列的示例代码:
```c
#define MAX_SIZE 10
int queue[MAX_SIZE];
int front = 0; // 队头指针
int rear = 0; // 队尾指针
// 入队操作
void enqueue(int x) {
if (rear == MAX_SIZE) {
printf("Queue is full\n");
return;
}
queue[rear++] = x;
}
// 出队操作
int dequeue() {
if (front == rear) {
printf("Queue is empty\n");
return -1;
}
return queue[front++];
}
```
使用链表实现队列的基本操作包括入队操作和出队操作,入队操作将元素插入到链表的末尾,出队操作将链表的第一个元素取出并删除它。
以下是使用链表实现队列的示例代码:
```c
struct Node {
int data;
struct Node* next;
};
struct Node* front = NULL; // 队头指针
struct Node* rear = NULL; // 队尾指针
// 入队操作
void enqueue(int x) {
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = x;
temp->next = NULL;
if (front == NULL && rear == NULL) {
front = rear = temp;
} else {
rear->next = temp;
rear = temp;
}
}
// 出队操作
int dequeue() {
if (front == NULL) {
printf("Queue is empty\n");
return -1;
}
struct Node* temp = front;
int x = temp->data;
if (front == rear) {
front = rear = NULL;
} else {
front = front->next;
}
free(temp);
return x;
}
```
以上就是用C语言实现队列的基本操作的方法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)
![](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)