c语言基于数组怎么实现队列
导读:基于数组实现队列可以使用两个指针front和rear来分别指向队列的头部和尾部。以下是一种使用数组实现队列的示例代码: #include <stdio.h> #define MAX_SIZE 100 typedef struc...
基于数组实现队列可以使用两个指针front和rear来分别指向队列的头部和尾部。以下是一种使用数组实现队列的示例代码:
#include stdio.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int front;
int rear;
}
Queue;
void initQueue(Queue *q) {
q->
front = -1;
q->
rear = -1;
}
int isEmpty(Queue *q) {
return (q->
front == -1 &
&
q->
rear == -1);
}
int isFull(Queue *q) {
return (q->
rear + 1) % MAX_SIZE == q->
front;
}
void enqueue(Queue *q, int value) {
if (isFull(q)) {
printf("Queue is full\n");
return;
}
if (isEmpty(q)) {
q->
front = 0;
q->
rear = 0;
}
else {
q->
rear = (q->
rear + 1) % MAX_SIZE;
}
q->
data[q->
rear] = value;
}
void dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return;
}
if (q->
front == q->
rear) {
q->
front = -1;
q->
rear = -1;
}
else {
q->
front = (q->
front + 1) % MAX_SIZE;
}
}
int front(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty\n");
return -1;
}
return q->
data[q->
front];
}
int main() {
Queue q;
initQueue(&
q);
enqueue(&
q, 5);
enqueue(&
q, 10);
enqueue(&
q, 15);
printf("Front element: %d\n", front(&
q));
dequeue(&
q);
printf("Front element: %d\n", front(&
q));
return 0;
}
在这个示例代码中,我们定义了一个Queue结构体来保存队列的数据和两个指针。initQueue函数用于初始化队列,isEmpty和isFull函数分别用于判断队列是否为空和是否已满。enqueue函数用于将元素入队,dequeue函数用于将队头元素出队,front函数用于获取队头元素的值。
在main函数中,我们首先初始化了队列,然后通过enqueue函数将3个元素入队。接着使用front函数获取队头元素的值,并通过dequeue函数将队头元素出队。最后再次使用front函数获取队头元素的值。
声明:本文内容由网友自发贡献,本站不承担相应法律责任。对本内容有异议或投诉,请联系2913721942#qq.com核实处理,我们将尽快回复您,谢谢合作!
若转载请注明出处: c语言基于数组怎么实现队列
本文地址: https://pptw.com/jishu/576573.html