SequenceQueue.h
#pragma once
#define ElemType char
#define QuenueSize 5
#define ERROR -1
#define OVERFLOW -2
typedef struct SequenceQueue {
ElemType* base;
int front;
int rear;
int size;
} Queue;
void InitQueue(Queue& Q);//初始化队列
void DestroyQueue(Queue& Q);//销毁队列
void ClearQueue(Queue& Q);//清空队列
bool EmptyQueue(Queue Q);//判断队列是否为空
ElemType* GetFront(Queue Q);//获取队首元素
void EnQueue(Queue& Q, ElemType e);//入队
void DeQueue(Queue& Q, ElemType& e);//出队
int QueueLength(Queue Q);//获取队列长度
void QueueTraverse(Queue Q, void(*f)(ElemType e));//遍历队列
SequenceQueue.c
#include <stdlib.h>
#include <stdio.h>
#include "SequenceQueue.h"
void InitQueue(Queue& Q) {
Q.base = (ElemType*)malloc(QuenueSize * sizeof(ElemType));
if (!Q.base) exit(OVERFLOW);
Q.size = QuenueSize;
Q.front = Q.rear = 0;
printf("init base address:%p,size:%d\n",Q.base,Q.size);
}
void DestroyQueue(Queue& Q) {
free(Q.base);
Q.front = Q.rear = 0;
}
void ClearQueue(Queue& Q) {
Q.front = Q.rear;
}
bool EmptyQueue(Queue Q) {
return Q.front == Q.rear ? true : false;
}
ElemType* GetFront(Queue Q) {
return Q.base + Q.front;//从0开始,
}
void EnQueue(Queue& Q, ElemType e) {
/*
判断表是否已满
假设表长度为2,有0,1两个位置
元素数量 头索引 尾索引
1 0 1
2 0 2%2=0 //此时队列满
3 0 1 //队列溢出
循环队列需要牺牲一个存储空间来判断队
队满条件:当队尾指针加1后与队首重合为队满
*/
if ((Q.rear + 1) % Q.size == Q.front) exit(OVERFLOW);//溢出退出程序,循环队列扩容比较麻烦,有时间单独研究下
*(Q.base + Q.rear) = e;
Q.rear=++Q.rear%Q.size;//队尾指向下次插入的位置
}
void DeQueue(Queue& Q, ElemType& e) {
if (EmptyQueue(Q)) exit(ERROR);
e = *(Q.base + Q.front++);
}
int QueueLength(Queue Q) {
return (Q.rear + Q.size - Q.front) % Q.size;
}
void QueueTraverse(Queue Q, void(*f)(ElemType e)) {
int cur = Q.front;
while (cur!=Q.rear)
{
f(*(Q.base+cur));
cur = ++cur % Q.size;
}
printf("queue base address:%p,size:%d,queue length:%d\n",Q.base,Q.size,QueueLength(Q));
}
main.c
#include "SequenceQueue.h"
#include <stdio.h>
#include <string.h>
#define EN "en"
#define DE "de"
#define GET "get"
#define EXIT "exit"
void PrintQueue(ElemType e) {
printf("%c\n", e);
}
int main() {
char opt[5], e = NULL;
Queue queue;
InitQueue(queue);
while (true)
{
gets_s(opt, 5);
if (strcmp(opt, EN) == 0) {
printf("wait for input:");
EnQueue(queue, getchar());
getchar();
}
else if (strcmp(opt, DE) == 0) {
DeQueue(queue, e);
printf("DE:%c\n", e);
}
else if (strcmp(opt, GET) == 0)
{
printf("GET:%c\n", *GetFront(queue));
}
else if (strcmp(opt, EXIT) == 0) {
DestroyQueue(queue);
break;
}
else {
printf("unkonw operation\n");
continue;
}
printf("queue:\n");
QueueTraverse(queue, PrintQueue);
}
}
来源:CSDN
作者:Quarrie
链接:https://blog.csdn.net/Quarrie/article/details/104245412