GPT答: |
7i24.cn
|
在C语言中,队列的rear()函数用于返回队列的尾部元素。具体用法如下:
1. 首先,需要定义一个队列结构体,并声明rear()函数:
```c
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
} Queue;
int rear(Queue *queue);
```
2. 在rear()函数中,通过访问队列的rear指针来获取尾部元素:
```c
int rear(Queue *queue) {
if (isEmpty(queue)) { // 判断队列是否为空
printf("Queue is empty.\n");
return -1; // 返回一个特殊值表示错误或空值
}
return queue->data[queue->rear]; // 返回尾部元素
}
```
注意事项:
- 在使用前需要先创建一个空的队列,并初始化front和rear指针。
- isEmpty()是判断队列是否为空的辅助函数,在此不做详细说明。
示例代码如下所示:
```c
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
} Queue;
void initQueue(Queue *queue) {
queue->front = -1; // 初始化头指针为-1(表示空)
queue->rear = -1; // 初始化尾指针为-1(表示空)
}
int isEmpty(Queue *queue) {
return queue->front == -1 && queue->rear == -1; // 头尾指针都为-1时为空
}
void enqueue(Queue *queue, int value) {
if (queue->rear == MAX_SIZE - 1) { // 队列已满
printf("Queue is full.\n");
return;
}
if (isEmpty(queue)) { // 队列为空时,需要同时更新头指针和尾指针
queue->front = 0;
queue->rear = 0;
} else {
queue->rear++; // 尾指针后移一位
}
queue->data[queue->rear] = value; // 将元素插入队尾
}
int rear(Queue *queue) {
if (isEmpty(queue)) { // 判断队列是否为空
printf("Queue is empty.\n");
return -1; // 返回一个特殊值表示错误或空值
}
return queue->data[queue->rear]; // 返回尾部元素
}
int main() {
Queue queue;
initQueue(&queue);
printf("Enqueuing elements: ");
for (int i = 1; i <= 5; i++) {
enqueue(&queue, i);
printf("%d ", rear(&queue));
}
return 0;
}
```
输出结果:
```
Enqueuing elements:
1
2
3
4
5
|