讲解讲解c++的队列用法
时间: 2023-09-04 18:06:36 浏览: 39
队列是一种先进先出(FIFO)的数据结构,在C语言中可以使用数组或链表来实现。
使用数组实现队列:
1. 定义一个数组和两个整型变量front和rear,分别表示队头和队尾的下标。
```c
#define MAX_SIZE 100
int queue[MAX_SIZE];
int front = 0;
int rear = -1;
```
2. 实现入队操作,将元素插入队尾,并将rear加1。
```c
void enqueue(int data) {
if (rear == MAX_SIZE - 1) {
printf("Queue is full.\n");
return;
}
queue[++rear] = data;
}
```
3. 实现出队操作,将队头元素弹出,并将front加1。
```c
int dequeue() {
if (front > rear) {
printf("Queue is empty.\n");
return -1;
}
return queue[front++];
}
```
4. 实现获取队头元素的操作,返回队头元素的值。
```c
int peek() {
if (front > rear) {
printf("Queue is empty.\n");
return -1;
}
return queue[front];
}
```
使用链表实现队列:
1. 定义一个链表结构体和两个指针变量front和rear,分别表示队头和队尾的节点。
```c
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* front = NULL;
Node* rear = NULL;
```
2. 实现入队操作,创建一个新节点并将其插入队尾,更新rear指针。
```c
void enqueue(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (rear == NULL) {
front = rear = newNode;
return;
}
rear->next = newNode;
rear = newNode;
}
```
3. 实现出队操作,弹出队头节点并将front指针向后移动一位。
```c
int dequeue() {
if (front == NULL) {
printf("Queue is empty.\n");
return -1;
}
int data = front->data;
Node* temp = front;
front = front->next;
if (front == NULL)
rear = NULL;
free(temp);
return data;
}
```
4. 实现获取队头元素的操作,返回队头节点的值。
```c
int peek() {
if (front == NULL) {
printf("Queue is empty.\n");
return -1;
}
return front->data;
}
```