数据结构(队列):循环队列

/*
	*数据结构(队列):循环队列
	*顺序存储
	*牺牲一个空间单元来判段队列满状态。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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值