循环队列-队列的顺序表示和实现

循环队列-队列的顺序表示和实现
使用一组地址连续的存储单元来保存队列元素,

并使用两个变量分别指向队列的前端和尾端

#include<stdio.h>
#define MAXNUM 100
#define OK 1
#define ERROR 0
#define Status int
#define ElemType int 
typedef struct{
	int front;//队头元素所在位置
	int rear;//队尾元素所在的下一个位置
	int queue[MAXNUM];//保存队列元素的数组 
}Queue;
void Init(Queue *q){
	q->front=0;
	q->rear=0;
}
//插入
Status EnQueue(Queue*q,ElemType elem){
	if((q->rear+1)%MAXNUM==q->front)
	return ERROR;
	//队列满,入队失败 
	q->queue[q->rear]=elem;//新元素入队
	q->rear=(q->rear+1)%MAXNUM;//队尾指针后移一位 
	return OK;
}
//删除
Status DeQueue(Queue*q,ElemType *pElem){
	if(q->front==q->rear)
	return ERROR;
	*pElem=q->queue[q->front];//队头出队 
	q->front=(q->front+1)%MAXNUM;//队头指针后移一位
	return OK; 
} 
int main(){
	Queue L;
	Init(&L);
	for(int i=0;i<10;i++){
		EnQueue(&L,i);
	}
	for(int j=0;j<10;j++){
		int t;
		DeQueue(&L,&t);
		printf("%d\n",t);
	}
	return 0;
}

含标志tag,提高效率

#include<stdio.h>
#define MAXNUM 10//队列元素个数为MAXNUM-1 
#define OK 1
#define ERROR 0
#define Status int
#define ElemType int 
typedef struct{
	int front;//队头元素所在位置
	int rear;//队尾元素所在的下一个位置
	int queue[MAXNUM];//保存队列元素的数组 
	int tag;
	//标志:区分尾指针和头指针值相同时,0为空,1为满 
}Queue;
void Init(Queue *q){
	q->front=0;
	q->rear=0;
	q->tag=0;
}
//插入
Status EnQueue(Queue*q,ElemType elem){
	if(q->tag)	
	return ERROR;
	//队列满,入队失败 
	q->queue[q->rear]=elem;//新元素入队
	q->rear=(q->rear+1)%MAXNUM;//队尾指针后移一位 
	if(q->rear==q->front)
	q->tag=1;
	return OK;
}
//删除
Status DeQueue(Queue*q,ElemType *pElem){
	if(q->front==q->rear&&q->tag==0)
	return ERROR;
	*pElem=q->queue[q->front];//队头出队 
	q->front=(q->front+1)%MAXNUM;//队头指针后移一位
	if(q->front==q->rear)
	q->tag=0;
	return OK; 
} 
int IS_Empty(Queue*q){
	if(q->front==q->rear&&q->tag==0)
	return 1;
	else
	return 0;
} 
int main(){
	Queue L;
	Init(&L);
	for(int i=0;i<10;i++){
		EnQueue(&L,i);
	}
	for(int j=0;j<10;j++){
		int t;
		DeQueue(&L,&t);
		printf("%d\n",t);
	}
	return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_40507857/article/details/80790257