#ifndef SQ_QUEUE_HEAD #define SQ_QUEUE_HEAD #include <stdio.h> #define Status int #define OVERFLOW -1 #define OK 0 #define ERROR 1 #define QUEUE_INIT_SIZE 10 typedef int ElemType; typedef struct { ElemType data[QUEUE_INIT_SIZE]; int front;//头指针,指向第一个元素 int rear;//尾指针,指向下一个可分配的单元 int size;//已分配的容量 } SqQueue; Status init(SqQueue *q) { q->front = 0; q->rear = 0; q->size = QUEUE_INIT_SIZE; return OK; } Status destroy(SqQueue *q) { q->front = 0; q->rear = 0; return OK; } Status push(SqQueue *q, ElemType e) { //队列满 if ((q->rear + 1) % q->size == q->front) return OVERFLOW; //将e写入尾指针指向的单元,然后尾指针后移 q->data[q->rear++] = e; //如果向后溢出则移到0号单元 if (q->rear == q->size) q->rear = 0; return OK; } Status pop(SqQueue *q, ElemType *e) { //队列空 if (q->rear == q->front) return OVERFLOW; //获取front指针指向的单元的值,然后front后移 *e = q->data[q->front++]; //将已出队的单元置0 q->data[q->front-1] = 0; //如果frong指针溢出则移到0号单元 if (q->front == q->size) q->front = 0; return OK; }
时间: 2024-10-14 06:08:34