用C++定义一个队列,并给出相应函数
时间: 2024-05-04 11:15:44 浏览: 10
很高兴回答你的问题。下面是一个用 C 语言定义队列的示例代码:
```
#define MAXSIZE 100 // 队列最大容量
typedef struct {
int data[MAXSIZE]; // 队列数据
int front; // 队首指针
int rear; // 队尾指针
} Queue;
// 初始化队列
void init(Queue *queue) {
queue -> front = queue -> rear = 0;
}
// 判断队列是否为空
int isEmpty(Queue *queue) {
return queue -> front == queue -> rear;
}
// 判断队列是否已满
int isFull(Queue *queue) {
return (queue -> rear + 1) % MAXSIZE == queue -> front;
}
// 入队操作
int enqueue(Queue *queue, int x) {
if (isFull(queue)) {
return 0; // 队列已满
}
queue -> data[queue -> rear] = x;
queue -> rear = (queue -> rear + 1) % MAXSIZE; // 队尾指针后移
return 1; // 入队成功
}
// 出队操作
int dequeue(Queue *queue, int *x) {
if (isEmpty(queue)) {
return 0; // 队列为空
}
*x = queue -> data[queue -> front];
queue -> front = (queue -> front + 1) % MAXSIZE; // 队首指针后移
return 1; // 出队成功
}
```
以上给出了队列的初始化、判断队列是否为空或已满、入队和出队操作的函数。
希望以上回答能够帮到你,如果还有问题请随时提出。