队列(Queue)是一个有序线性表,但队列的插入和删除操作是分别在线性表的两个不同端点进行的。
操作集
- Queue CreateQueue(int MaxSize)
- bool IsFull(Queue Q)
- bool AddQ(Queue Q, ElementType X)
- bool IsEmpty(Queue Q)
- ElementType DeleteQ(Queue Q)
1.队列的顺序存储实现
typedef int Position;
typedef struct QNode *PtrToQNode;
struct QNode{
ElementType *Data;
Position Front, Rear;
int MaxSize;
};
typedef PtrToQNode Queue;
1.1 创建队列
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;
reutrn Q;
}
1.2 插入队列
bool IsFull(Queue Q){
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;
}
}
1.3 删除队列
bool IsEmpty(Queue Q){
return(Q->Front == Q->Rear);
}
ElementType DeleteQ(Queue Q){
if(IsRmpty(Q)){
printf("队列空");
return ERROR;
}
else{
Q->Front = (Q->Front+1)%Q->MaxSize;
return Q->Data[Q->Front];
}
}
2.队列的链式存储实现
typedef struct Node * PtrToNode;
struct Node{
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode Position;
typedef struct QNode * PtrToQNode;
struct QNode{
Position Front, Rear;
//int MaxSize; //队列的最大容量,
//若有MaxSize, 不知道如何判别队列IsFull
};
typedef PtrToQNode Queue;
- 注意,我实现的是不带头结点的链式,带头结点
2.1 创建队列
Queue CreateQueue(){
Queue Q = (Queue)malloc(sizeof(struct QNode));
Q->Front = Q->Rear = NULL;
reutrn Q;
}
2.2 链式入队 (不带头结点)
//若有IsFull
bool IsFull(Queue Q){
}
bool AddQ(Queue Q, ElementType X)
TmpCell = (PtrToNode)malloc(sizeof(struct Node));
TmpCell->Data = X;
TmpCell->Next = NULL;
if(Q->Front == NULL){ //队列为空,要特殊处理
Q->Front = TmpCell;
Q->Rear = TmpCell;
}
else{
Q->Rear->Next = TmpCell;
Q->Rear = TmpCell;
}
return true;
}
2.3 链式出队(不带头结点)
bool 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 = ForntCell->Data;
free(FrontCell);
return FrontElem;
}
}