#include<stdio.h>
#include<malloc.h>
#include<windows.h>
#define MaxSize 50
//構(gòu)造環(huán)形隊列的數(shù)據(jù)類型
typedef char ElemType;
struct queue
{
?ElemType data[MaxSize];//順序存儲數(shù)據(jù)元素
?int front,rear;//分別是隊首隊尾的指示器
};
typedef struct queue Queue;
/*
函數(shù)功能:InitQueue,初始化空隊列
函數(shù)形參:Queue *&Q
函數(shù)返回值:無
*/
void InitQueue(Queue *&Q)
{
?//初始化空隊列,申請起始地址,并初始化兩個指示器的位置
?Q=(Queue *)malloc(sizeof(Queue));
?Q->front=Q->rear=0;
}
/*
函數(shù)功能:QueueEmpty,1代表空隊列,0代表非空隊列
函數(shù)形參:Queue *Q
函數(shù)返回值:int
*/
int QueueEmpty(Queue *Q)
{
?return (Q->front==Q->rear);
}
/*
函數(shù)功能:enQueue 入隊
函數(shù)形參:Queue*Q,ElemType e入隊元素值
函數(shù)返回值:若隊滿則返回0表示入隊失敗,否則返回1,入隊成功
*/
int enQueue(Queue *Q,ElemType e)
{
?//判斷隊是否滿
?if((Q->rear+1)%MaxSize==Q->front) return 0;//入隊失敗
?//入隊,隊尾指示器加1,元素入隊
?Q->rear=(Q->rear+1)%MaxSize;
?Q->data[Q->rear]=e;
?return 1;//入隊成功
}
/*
函數(shù)功能:deQueue,出隊
函數(shù)形參:Queue *Q,ElemType &e臨時存放被出隊元素
函數(shù)返回值:若隊空則返回0表示出隊失敗,否則返回1,出隊成功
*/
int deQueue(Queue *Q,ElemType &e)
{
?//判斷隊是否空
?if(Q->front==Q->rear) return 0;
?//出隊
?//e=Q->data[(Q->front+1)%MaxSize];
?Q->front=(Q->front+1)%MaxSize;
?e=Q->data[Q->front];
?return 1;//出隊成功
}
/*
函數(shù)功能:DestroyQueue 釋放內(nèi)存
函數(shù)形參:Queue *Q
函數(shù)返回值:無
*/
void DestroyQueue(Queue *&Q)
{
?free(0);
?Q=NULL;
}
/*
函數(shù)功能:DispQueue從隊首到隊尾打印所有元素
函數(shù)形參:Queue *Q
函數(shù)返回值:無
*/
void DispQueue(Queue *&Q)
{
?int i;
?for(i=Q->front;i<Q->rear;i++)
??printf("%c ",Q->data[i+1]);
?printf("\n");
}
void QueueLength(Queue *Q,int &a)
{
?a=(Q->rear-Q->front+MaxSize)%MaxSize;
}
int main()
{
?Queue *Q;ElemType e,a;int b;
?printf("(1)環(huán)形隊列初始化。。。\n");InitQueue(Q);
?printf("(2)環(huán)形隊列當(dāng)前狀態(tài)是:");
?if(QueueEmpty(Q)==1) printf("空隊\n");
?else???????????????? printf("非空隊\n");
?printf("(3)元素入隊\n");
?if(enQueue(Q,'A')==1) printf("入隊成功\n");
?else???????????????? printf("入隊失敗\n");
?if(enQueue(Q,'B')==1) printf("入隊成功\n");
?else???????????????? printf("入隊失敗\n");
?if(enQueue(Q,'C')==1) printf("入隊成功\n");
?else???????????????? printf("入隊失敗\n");
?printf("(4)環(huán)形隊列當(dāng)前狀態(tài)是:");
?if(QueueEmpty(Q)==1) printf("空隊\n");
?else???????????????? printf("非空隊\n");
?printf("打印元素\n");DispQueue(Q);
?printf("統(tǒng)計長度\n");QueueLength(Q,b);
?printf("%d",b);
?printf("(5)元素出隊");
?if(deQueue(Q,e)==1) printf("出隊成功,出隊元素為:%c\n",e);
?else??????????????? printf("出隊失敗");
?printf("(6)銷毀隊列\(zhòng)n");DestroyQueue(Q);
?system ("PAUSE");
?return 0;
}