队列
1 什么是队列
队列(Queue):具有一定操作约束的线性表;
插入和删除操作:只能在一端插入,而在另一端删除。
数据插入:入队列(AddQ)
数据删除:出队列(DeleteQ)
先来先服务
先进先出:FIFO
2 队列的抽象数据类型
类型名称:队列(Queue)
数据对象集: 一个有0个或多个元素的有穷线性表。
操作集: 长度为MaxSize的队列Q Queue,队列元素item ElementType
- Queue CreatQueue( int MaxSize ):生成长度为MaxSize的空队列;
- int IsFullQ( Queue Q, int MaxSize ):判断队列Q是否已满;
- void AddQ( Queue Q, ElementType item ): 将数据元素item插入队列Q中;
- int IsEmptyQ( Queue Q ): 判断队列Q是否为空;
- ElementType DeleteQ( Queue Q ):将队头数据元素从队列中删除并返回。
3 队列的顺序存储实现
队列的顺序存储结构通常由一个一维数组和一个记录队列头元
素位置的变量front以及一个记录队列尾元素位置的变量rear组成。
头尾相接的顺序存储结构称为 循环队列
顺序存储结构代码
typedef int Position;
struct QNode {
ElementType *Data; /* 存储元素的数组 */
Position Front, Rear; /* 队列的头、尾指针 */
int MaxSize; /* 队列最大容量 */
};
typedef struct QNode *Queue;
创造一个队列
Queue CreateQueue( int MaxSize )
{
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q->Data = (ElementType *)malloc(MaxSize * sizeof(ElementType));
Q->Front = Q->Rear = 0;
Q->MaxSize = MaxSize;
return Q;
}
插入
int IsFull( Queue Q )
{
return ((Q->Rear+1)%Q->MaxSize == Q->Front);
}
void AddQ( Queue Q, ElementType X )
{
if ( IsFull(Q) ) {
printf("队列满");
return false;
}
else {
Q->Rear = (Q->Rear+1)%Q->MaxSize;
Q->Data[Q->Rear] = X;
return true;
}
}
删除
int IsEmpty( Queue Q )
{
return (Q->Front == Q->Rear);
}
ElementType DeleteQ( Queue Q )
{
if ( IsEmpty(Q) ) {
printf("队列空");
return ERROR;
}
else {
Q->Front =(Q->Front+1)%Q->MaxSize;
return Q->Data[Q->Front];
}
}
4 队列的链式存储结构及实现
队列的链式存储结构也可以用一个单链表实现。插入和删除操作
分别在链表的两头进行;对头指针指向链队列的头节点,队尾指针指向终端节点
链式存储结构代码
typedef struct Node *PtrToNode;
struct Node { /* 队列中的结点 */
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode Position;
struct QNode {
Position Front, Rear; /* 队列的头、尾指针 */
int MaxSize; /* 队列最大容量 */
};
typedef struct QNode *Queue;
插入
void AddQ( Queue Q, ElementType item )
{
PtrToNode s=(PtrToNode)malloc(sizeof(Node));
if(!s) /*存储分配失败*/
exit(OVERFLOW)
s->Data=item;
s->next=NUll;
Q->rear->next=s;
Q->rear=s;
return Q
}
删除
int IsEmpty( Queue Q )
{
return ( Q->Front == NULL);
}
ElementType DeleteQ( Queue Q )
{
Position FrontCell;
ElementType FrontElem;
if ( IsEmpty(Q) ) {
printf("队列空");
return ERROR;
}
else {
FrontCell = Q->Front;
if ( Q->Front == Q->Rear ) /* 若队列只有一个元素 */
Q->Front = Q->Rear = NULL; /* 删除后队列置为空 */
else
Q->Front = Q->Front->Next;
FrontElem = FrontCell->Data;
free( FrontCell ); /* 释放被删除结点空间 */
return FrontElem;
}
}