队列——循环队列
一般队列的顺序存储如图
这种队列顺序存储和插入元素用头插法的顺序表的顺序存储简直一模一样,不过在顺序表的顺序存储的数组的有值部分的最右边加一个对标记(图中多了一个标记),即可。
循环队列会更加方便入队和出队,不过作为顺序存储,循环队列面临着数组可能会溢出的问题。还是来看看,循环队列的图吧。
循环队列的抽象数据类型
> init_Queue(&Q); 初始化队列
>
> En_Queue(&Q); 入队操作
>
> print_Queue(Q); 打印队列
>
> len_Queue(Q); 计算队列的长度
>
> De_Queue(&Q, &e); 出队操作
代码
#include <stdio.h>
#define MAXSIZE 20
typedef int ElemType;
typedef struct
{
ElemType data[MAXSIZE];
int Front; //This is head pointer
int Rear; //This is tail pointer
}SqQueue;
void init_Queue(SqQueue *Q)
{
Q->Front = 0;
Q->Rear = 0;
}
void En_Queue(SqQueue *Q)
{
int e;
int n;
if ((Q->Rear + 1) % MAXSIZE == Q->Front)
{
printf("Enqueue opertion is failed !\n");
return;
}
printf("Please enter the number of elements to be enqueued: ");
scanf("%d", &n);
if (n > MAXSIZE - 1)
{
printf("The number is out of range!\n");
return;
}
for(int i = 0; i < n; i++)
{
printf("Please enter element to be enqueued: ");
scanf("%d", &e);
Q->data[Q->Rear] = e;
Q->Rear = (Q->Rear + 1) % MAXSIZE;
}
}
void print_Queue(SqQueue Q)
{
if (Q.Front == Q.Rear)
{
printf("The queue is empty !\n");
return;
}
for (int i = Q.Front; i != Q.Rear;)
{
printf(" %d ", Q.data[i]);
i = (i + 1) % MAXSIZE;
}
printf("\n");
}
void De_Queue(SqQueue *Q, ElemType *e)
{
if (Q->Front == Q->Rear)
{
printf("The queue is empty !\n");
return;
}
*e = Q->data[Q->Front];
Q->Front = (Q->Front + 1) % MAXSIZE;
}
int len_Queue(SqQueue Q)
{
return (Q.Rear - Q.Front + MAXSIZE) % MAXSIZE;
}
int main()
{
SqQueue Q;
//Initialization queue
init_Queue(&Q);
//Enqueue opertion of the circular queue
En_Queue(&Q);
//Print queue contents
print_Queue(Q);
//Calculate the length of the circular queue
int len = 0;
len = len_Queue(Q);
printf("The queue`s length is %d\n", len);
//Dequeue opertion of the circular queue
ElemType e;
De_Queue(&Q, &e);
printf("The value to be dequeued is %d\n", e);
print_Queue(Q);
len = len_Queue(Q);
printf("The queue`s length is %d\n", len);
return 0;
}