队列是只允许在一端进行插入操作,而在另一端进行删除操作的线性表,是一种先进先出
的线性表,简称“FIFO”
。
顺序存储队列
入列只需要在队尾加入,时间复杂度为O(1)
;出列需要移动后面所以的元素,时间复杂度为O(n)
。
为了避免出列移动所有元素,可以让队头不在下标为0
的位置。
为了避免当只有一个元素时,队头和队尾重合,所以引入两个指针,front指向队头,rear指向队尾元素的下一个位置,当front=rear时,队列为空
。
如下会出现假溢出
的情况:
循环队列的顺序存储结构
为了解决“假溢出”
,可以让后面满了,再从头开始,也就是头尾相接的循环。
front=rear,为空还是满?
方法1
:引入一个标志变量flag
,当front==rear,flag=0时,队列为空
,flag=1时,队列为满
。
方法2
:
(1)队列满的条件:(rear+1)%QueueSize==front
(2)队列长度:(rear-front+QueueSize)%QueueSize
#include "stdio.h"
#include "stdlib.h"
#include "io.h"
#include "math.h"
#include "time.h"
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20 /* 存储空间初始分配量 */
typedef int Status;
typedef int QElemType; /* QElemType类型根据实际情况而定,这里假设为int */
/* 循环队列的顺序存储结构 */
typedef struct
{
QElemType data[MAXSIZE];
int front; /* 头指针 */
int rear; /* 尾指针,若队列不空,指向队列尾元素的下一个位置 */
}SqQueue;
Status visit(QElemType c)
{
printf("%d ", c);
return OK;
}
/* 初始化一个空队列Q */
Status InitQueue(SqQueue *Q)
{
Q->front = 0;
Q->rear = 0;
return OK;
}
/* 将Q清为空队列 */
Status ClearQueue(SqQueue *Q)
{
Q->front = Q->rear = 0;
return OK;
}
/* 若队列Q为空队列,则返回TRUE,否则返回FALSE */
Status QueueEmpty(SqQueue Q)
{
if (Q.front == Q.rear) /* 队列空的标志 */
return TRUE;
else
return FALSE;
}
/* 返回Q的元素个数,也就是队列的当前长度 */
int QueueLength(SqQueue Q)
{
return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}
/* 若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR */
Status GetHead(SqQueue Q, QElemType *e)
{
if (Q.front == Q.rear) /* 队列空 */
return ERROR;
*e = Q.data[Q.front];
return OK;
}
/* 若队列未满,则插入元素e为Q新的队尾元素 */
Status EnQueue(SqQueue *Q, QElemType e)
{
if ((Q->rear + 1) % MAXSIZE == Q->front) /* 队列满的判断 */
return ERROR;
Q->data[Q->rear] = e; /* 将元素e赋值给队尾 */
Q->rear = (Q->rear + 1) % MAXSIZE;/* rear指针向后移一位置, */
/* 若到最后则转到数组头部 */
return OK;
}
/* 若队列不空,则删除Q中队头元素,用e返回其值 */
Status DeQueue(SqQueue *Q, QElemType *e)
{
if (Q->front