类型名称: 队列
数据对象集: 一个有0个或者多个元素的有穷线性表
操作集: 对于一个长度为长整数MaxSize的队列Q,记队列中的任一元素X,队列的基本操作有:
1:Queue CreateQueue(int MaxSize):生成空队列,其最大长度为:MaxSize;
2:bool IsFull(Queue Q):判断队列Q是否为空,若是返回true,否则返回false;
3:bool AddQ(Queue Q,ElementType X):将元素X压入队列Q。若队列已满,返回false;否则将数据元素X插入队列Q并返回true;
4:bool IsEmpty(Queue Q):判断队列Q是否为空,若是返回true;否则返回false;
5:ElementType DeleteQ(Queue Q):删除并返回队列头元素。若队列为空,返回错误信息;否则将队列头数据元素从队列中删除
队列的顺序存储实现:
结构实现:
typedef int Position;
typedef int ElementType;
typedef struct QNode* PtrToQNode;
struct QNode {
ElementType* Data;//存储元素的数组
Position Front, Rear;//队列的头尾指针
int MaxSize;//队列的最大容量
};
循环队列的创建与插入和删除,判满判空操作的实现:
Queue CreateQueue(int MaxSize) {
Queue Q = (Queue)malloc(sizeof(struct QNode));//创建队列结构
Q->Data = (ElementType*)malloc(MaxSize * sizeof(ElementType));//创建队列储存数据的数组结构,并把指针赋值给Data
Q->Front = Q->Rear=0;//头和尾都指向0
return Q;
}
bool IsFull(Queue Q) {//判满方法:少用一个元素空间。队满条件:(Rear+1)%数组长度=Front 队列空条件:Rear=Front
return ((Q->Rear + 1) % Q->MaxSize == Q->Front);
}
bool 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;
}
}
bool IsEmpty(Queue Q) {
return (Q->Front == Q->Rear);
}
ElementType Delete(Queue Q) {
if (IsEmpty(Q)) {
printf("队列空!");
return ERROR;
}
else {
Q->Front = (Q->Front + 1) % Q->MaxSize;
return Q->Data[Q->Front];
}
}
队列的链式存储实现:
typedef struct Node* PtrToNode;
struct Node {//队列中的结点
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode Position;
typedef struct QNode* PtrToQNode;
struct QNode {
Position Front, Rear;
int MaxSize;
};
typedef PtrToQNode Queue;
不带头结点的链式队列操作实例:
bool IsEmpty(Queue Q) {
//return Q->Front == Q->Rear;//这样比较不是说明队列空,而是队列只有一个元素
return (Q->Front == NULL);
}
ElementType DeleteQ(Queue Q) {
Position FirstCell;
ElementType FrontElem;
if (IsEmpty(Q))
{
printf("队列空!");
return ERROR;
}
else
{
/*FirstCell = Q->Front;
Q->Front = Q->Front->Next;
FrontElem = FirstCell->Data;
free(FirstCell);
return FrontElem;*/
FirstCell = Q->Front;
if (Q->Front==Q->Rear)
{
Q->Front = Q->Rear = NULL;
}
else
{
Q->Front = Q->Front->Next;
FrontElem = FirstCell->Data;
free(FirstCell);
return FrontElem;
}
}
}