queue的链表实现
#include <stdlib.h>
#include<stdio.h>
#define ERROR -9999
typedef int ElementType;
typedef struct Node* PtrToNode;
struct Node{
ElementType Data;
PtrToNode Next;
};
typedef PtrToNode Position;
typedef struct QNode* PtrToQNode;
struct QNode{
Position Rear,Front;
int MaxSize;
};
typedef PtrToQNode Queue;
Queue CreateQueue(int MaxSize){
Queue Q = (Queue) malloc(sizeof(struct QNode));
Q->MaxSize = MaxSize;
Q->Front=Q->Rear=NULL;
return Q;
}
bool IsEmpty(Queue Q){
if(Q->Front ==NULL){
return true;
}else{
return false;
}
}
bool IsFull(Queue Q){
PtrToNode firstNode = Q->Front;
int counts = 1;
while(firstNode != Q->Rear){
firstNode = firstNode->Next;
counts++;
}
if(counts == Q->MaxSize){
return true;
}else{
return false;
}
}
ElementType DeleteQ(Queue Q){
PtrToNode frontNode ;
ElementType frontNodeData;
if(IsEmpty(Q)){
printf("该队列已经为空");
return ERROR;
}
frontNode = Q->Front;
if(Q->Front == Q->Rear){
Q->Front=Q->Rear=NULL;
}else{
Q->Front = Q->Front->Next;
}
frontNodeData = frontNode->Data;
free(frontNode);
printf("%d 已经出队",frontNodeData);
return frontNodeData;
}
bool AddQ(Queue Q,ElementType X)
{
PtrToNode newNode = (PtrToNode) malloc(sizeof(struct Node));
newNode->Data = X;
if(IsFull(Q)){
printf("不能使用AddQ%d,因为队列已经满了\n",X);
return false;
} else if(IsEmpty(Q)){
Q->Front = Q->Rear = newNode;
}else{
newNode->Data = X;
newNode->Next = NULL;
Q->Rear->Next = newNode;
Q->Rear = newNode;
}
printf("%d 已经进入队列\n",X);
return true;
}
int main(){
int numbers = 15;
Queue Q = CreateQueue(numbers);
for(int i = 0; i<Q->MaxSize;i++){
AddQ(Q,i);
}
int num ;
for(int j = 0; j<Q->MaxSize;j++){
num = DeleteQ(Q);
if(num != ERROR){
printf("%d\n",num);
}
}
return 0;
}