一、队列的结构定义
#define MaxSize 100
#define DataType int
typedef struct {
DataType data[MaxSize];
int front, rear;
}SeqQueue, * PSeqQueue;
二、基本操作的实现
//初始化队列
PSeqQueue Init_Queue() {
PSeqQueue Q;
Q = (PSeqQueue)malloc(sizeof(SeqQueue));
if (Q) {
Q->front = 0;
Q->rear = 0;
printf("初始化成功\n");
}
return Q;
}
//判空
int Empty_Queue(PSeqQueue Q) {
if (Q->front == Q->rear)
return 1; //队空
return 0; //不空
}
//入队
int In_Queue(PSeqQueue Q, DataType x) {
if ((Q->rear + 1) % MaxSize == Q->front)
return 0; //队满
Q->data[Q->rear] = x;
Q->rear = (Q->rear + 1) % MaxSize;
return 1; //成功
}
//出队,用x保存出队元素
int Out_Queue(PSeqQueue Q, DataType* x) {
if (Empty_Queue(Q))
return 0; //队空
*x = Q->data[Q->front];
Q->front = (Q->front + 1) % MaxSize;
return 1; //成功
}
//读队头元素
int Front_Queue(PSeqQueue Q, DataType* x) {
if (Empty_Queue(Q))
return 0; //队空
*x = Q->data[Q->front];
}
//销毁队列
void Destroy_Queue(PSeqQueue* Q) {
if (*Q) {
free(*Q);
*Q = NULL;
printf("销毁成功\n");
}
}
//队列所有元素
void Show_Queue(PSeqQueue Q) {
printf("队中元素有:\n");
for (int i = Q->front; (i % MaxSize) < Q->rear; i++) {
printf("%d ", Q->data[i]);
}
printf("\n");
}
三、测试代码
/*
循环队列
为了方便判断队满,牺牲一个存储空间,
队满条件为:(rear + 1) % MaxSize == front
*/
int main() {
int x;
PSeqQueue Q;
Q = Init_Queue();
if (Empty_Queue(Q))
printf("队空\n");
else
printf("队不空\n");
for (int i = 0; i < 5; i++) {
if (In_Queue(Q, i))
printf("入队成功,入队元素为:%d\n", i);
}
Show_Queue(Q);
if (Empty_Queue(Q))
printf("队空\n");
else
printf("队不空\n");
if (Out_Queue(Q, &x))
printf("出对成功,出队元素为:%d\n", x);
Show_Queue(Q);
if (Front_Queue(Q, &x))
printf("对头元素为:%d\n", x);
Destroy_Queue(&Q);
return 0;
}
四、测试结果