/*
*数据结构(队列):循环队列
*顺序存储
*牺牲一个空间单元来判段队列满状态。Q.front == (Q.rear+1)%InitSize
*Date:2017/4/16
*/
#include <stdio.h>
#define ElemType char
#define InitSize 100
typedef struct{
ElemType data[InitSize];
int front,rear;
}SqQueue;
void initQueue(SqQueue &Q); //初始化队列
bool emptyQueue(SqQueue Q); //判空操作
bool isFullQueue(SqQueue Q); //判断队列Q是否满了
void EnQueue(SqQueue &Q,ElemType e); //入队
void DeQueue(SqQueue &Q,ElemType &e); //出队
void getHead(SqQueue Q,ElemType &e); //获取队头元素值
void printQueue(SqQueue Q); //打印队列
void clearQueue(SqQueue &Q); //清空队列
void initQueue(SqQueue &Q){
ElemType c;
Q.front = Q.rear = 0;
while(scanf("%c",&c) != EOF && c != '\n'){
if(!isFullQueue(Q)){
Q.data[Q.rear] = c;
Q.rear++;
}
}
}
bool emptyQueue(SqQueue Q){
if(Q.front == Q.rear){
return true;
}else{
return false;
}
}
bool isFullQueue(SqQueue Q){
if((Q.rear+1)%InitSize == Q.front){
return true;
}else{
return false;
}
}
void EnQueue(SqQueue &Q,ElemType e){
if(!isFullQueue(Q)){
Q.data[Q.rear] = e;
Q.rear = (Q.rear + 1) % InitSize;
}
}
void DeQueue(SqQueue &Q,ElemType &e){
if(!emptyQueue(Q)){
e = Q.data[Q.front];
Q.front = (Q.front + 1) % InitSize;
}
}
void getHead(SqQueue Q,ElemType &e){
if(!emptyQueue(Q))
e = Q.data[Q.front];
}
void printQueue(SqQueue Q){
int i = Q.front;
while(i != Q.rear){
printf("%c",Q.data[i]);
i = (i+1)%InitSize;
}
printf("\n");
}
void clearQueue(SqQueue &Q){
Q.front = Q.rear;
printf("队列已经清空\n");
}
int main(){
freopen("in.txt","r",stdin);
SqQueue Q;
ElemType e;
initQueue(Q);
printQueue(Q);
EnQueue(Q,'A');
printf("EnQueue(&Q,'A'):\n");
printQueue(Q);
DeQueue(Q,e);
printf("DeQueue(&Q,e):%c\n",e);
printQueue(Q);
getHead(Q,e);
printf("getHead(Q,e):%c\n",e);
if(emptyQueue(Q)){
printf("Q is NULL\n");
}else{
printf("Q isn't NULL\n");
}
clearQueue(Q);
if(emptyQueue(Q)){
printf("Q is NULL\n");
}else{
printf("Q isn't NULL\n");
}
return 0;
}
in.txt:
peer