//循环队列的实现
//ch1_4
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 5 //队列的最大长度
typedef int elemType;
//循环队列
typedef struct {
elemType* base;
int front; //队首指针,删除队首元素,头指针加1
int rear; //队尾指针,插入队尾元素,尾指针加1
}SqQueue;
//构造队列
void initQueue(SqQueue* S)
{
S->base = (elemType*)malloc(sizeof(elemType) * MAX_SIZE);
if (!S->base) exit(1);
else S->front = S->rear = 0; //空队列时,首位指针都为0
}
//获取元素个数
int getLength(SqQueue* S)
{
//%MAX_SIZE为循环队列特有,保证大于时,可以从头开始
return (S->rear - S->front + MAX_SIZE) % MAX_SIZE;
}
//删除队首元素
void insertElem(SqQueue* S, elemType data)
{
//留一个元素位来判断是否已满
if ((S->rear + 1) % MAX_SIZE == S->front)//队列满的标志
{
printf("队列空间已满,插入元素失败!");
}
else
{
S->base[S->rear] = data;
printf("插入成功:%d\n", S->base[S->rear]);
S->rear = (S->rear + 1) % MAX_SIZE;
}
}
//队尾插入元素
void deleteElem(SqQueue* S)
{
if (S->front == S->rear)//空队列标志
{
printf("空队列,删除元素失败!\n");
}
else
{
printf("删除了队首元素:%d\n", S->base[S->front]);
S->front = (S->front + 1) % MAX_SIZE;
}
}
//遍历队列
void printdui(SqQueue a) {
if (a.front==a.rear)
return -1;
if (a.front < a.rear) {
for (int i = a.front; i < a.rear; i++)
printf("%d ", a.base[i]);
}
else {
for (int i = a.front; i < a.rear + MAX_SIZE; i++)
printf("%d ", a.base[i % MAX_SIZE]);
}
printf("\n");
return 0;
}
int main()
{
printf("队列最大空间为5,存放元素个数为4\n");
SqQueue S;
initQueue(&S);
insertElem(&S, 5);
insertElem(&S, 6);
insertElem(&S, 7);
insertElem(&S, 8);
insertElem(&S, 9); //插入失败
printf("\n此时队列共有%d个元素\n", getLength(&S));
printdui(S);
deleteElem(&S);
deleteElem(&S);
printf("\n此时队列共有%d个元素\n", getLength(&S));
printdui(S);
insertElem(&S, 3);
insertElem(&S, 4);
printf("\n此时队列共有%d个元素\n", getLength(&S));
printdui(S);//遍历队列
return 0;
}
《数据结构复习》循环队列
最新推荐文章于 2023-01-14 22:17:00 发布