队列的顺序存储结构——数组实现;
如果每次删除一个队列元素时,都需要把剩余元素左移一个位置,则时间复杂度会增加为O(n);
如果每次删除一个队列元素,只把队首加1,时间复杂度会减少为O(1),但无法用到队首之前的空间;
对于队列的顺序存储结构,一般采用循环队列,把数组视为一个环,把数组的两端连接。可以同时解决上述两个问题;
但为了避免无法判断队列是空还是满,队列不能插满。
代码实现:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 10 //队列总的可用空间
typedef int ElemType;
typedef struct SEQUENCEQUEUE
{
int front; //队首位置
int rare; //队尾位置
ElemType *base; //分配内存的基地址
int Maxsize; //存储容量
}cycleQueue;
void InitQueue(cycleQueue *q) //初始化
{
q->base = (ElemType*)malloc(MAXSIZE * sizeof(ElemType));
if (!q->base)
{
exit(0);
}
q->front = q->rare = 0;
q->Maxsize = MAXSIZE;
}
void PushQueue(cycleQueue *q, ElemType e) //入队列
{
if ((q->rare + 1) % q->Maxsize == q->front)
{
printf("队列已满 \n");
exit(0);
}
q->base[q->