一,什么是队列?
队列是只允许在一端进行插入操作,而在另一端进行删除操作的线性表。队列先进先出(FIFO),允许插入的一端为队尾,允许删除的一端为队头。
二,队列顺序存储有什么不足?
一个队列里有n个元素,顺序队列需要建立一个大于n的数组,并把所有元素存储在前n个单元,数组下标为0的一端为队头。
当需要插入元素时,只需将元素插入队尾,但当需要输出元素时,将队头元素输出后,需要将后面的元素全部向前移动。
三,什么是假溢出?
为了避免在删除队头时将后面元素向前移动,引入两个指针,front 和rear 指针,均指向下标为零的位置,当插入元素时,front指针不变,rear指针指向队尾元素后一个,当删除元素时,front指向删除后的第一个元素。但当数组已满,rear无法指向下一个位置,产生数组越界,但此时,有可能front指针前面位置空闲。这种情况称为假溢出。
四,什么是循环队列?
头尾相接的顺序循环队列称为循环队列。当出现假溢出,再从头开始,rear改为指向下标0的位置。当下标为0位置插入元素,rear指向下一个。
当rear 和 front相等时,如何判断队列满还是空?
1、设置标志变量flag,front==rear时,flag为零则为空,flag为一则为满。
2、当队列空时,条件就是front==rear,当队列满时,修改条件,保留一个元素空间。
3、队列满的条件为(rear+1)%QueueSize==front 通用计算队列长度的公式为(rear-front+QueueSize)%QueueSize.
五,循环队列
typedef int DataType;
typedef struct sqQueue
{
DataType data[MAXSIZE];
int front;
int rear;
} ;
typrdef struct sqQueue SqQueue;
初始化:
Status InitQueue(SqQueue *Q)
{
Q -> front = 0;
q - > rear = 0;
return success;
}
求队伍长度:
int QueueLength(SqQueue Q)
{
return (Q.rear -Q.front + MAXSIZE) % MAXSIZE;
}
入队伍:
Status EnQueue (Squeue *Q,QElemType e)
{
if((Q ->rear +1) %MAXSIZE == Q -> front)
{return failure;}
Q -> data[Q -> rear] = e;
Q ->rear = (Q -> rear +1) %MAXSIZE;
return success;
}
出队伍:
Status DeQueue (Squeue *Q,QElemType *e)
{
if (Q -> front ==Q ->rear)
return failure;
*e = Q ->data[Q -> front];
Q -> front = (Q ->front+1) %MAXSIZE;
return sccess;
}
六,队伍的链式存储结构及实现
typedef int QElemType
typrdef struct Qnode
{
QElemType data;
struct Qnode *next;
};
struct Qnode *QueuePtr;
typedef struct
{QueuePtr front,rea;
}LinkQueue;
Status EnQueue (LinkQueue *q,QElemType e)
{
QueuePtr s = (QueuePtr)malloc(sizeof(Qnode0));
if (!s)
exit (overflow);
s ->data = e;
s ->next = NULL;
Q ->rear->next =s;
Q ->rear = s;
return success;