循环队列全部操作实现代码(C语言)

版权声明:原创的东西,转载时留个标记。 https://blog.csdn.net/laguoqing/article/details/84960505

栈和队列不愧为亲兄弟,在栈的实现基础上简单改改即可实现队列全部操作,加上循环二字,也就是多了个%取余(模)运算,放上成果,立码为证:

/*
实现循环队列的全体操作
						*/
#include "stdio.h"
#define MAXSIZE    50
#define TRUE       1
#define FALSE      0
 
typedef int bool;       //Cpp中这一行要取消掉,他内置bool型 
typedef int Status;    //函数类型,其值是函数结果状态码
typedef int ElemType;  //数据类型 
 
 
typedef struct queue
{
	ElemType Data[MAXSIZE];
	int front,rear;
}SqQueue;
 
 
void InitQueue(SqQueue *q)//初始化队列
{
	 q->rear=q->front=0; //一定要赋值,否则会出野指针 
}
 
bool QueueEmpty(SqQueue *q)//判队空 
{
	if(q->rear==q->front)
		return TRUE;
	else
		return FALSE;
}
 
bool EnQueue(SqQueue *q,ElemType e)//入队 
{
	if((q->rear+1)%MAXSIZE==q->front)  //队满 
	    {
    	printf("Queue is Full\n");   	
		return FALSE;
	    }
	    q->Data[q->rear]=e;
		q->rear=(q->rear+1)%MAXSIZE;//队尾指针加1取模 
		printf("EnQueue data %d into Queue \n",e);
	    return TRUE;
}
bool  DeQueue(SqQueue *q,ElemType *e)//出队 
{
	if(q->rear==q->front)
	    {
    	printf("Queue is Empty\n");   	
		return FALSE;
	    }
		*e=q->Data[q->front];//先取数再移指针 
		q->front=(q->front+1)%MAXSIZE;  //队头指针加1取模  
		printf("DeQueue data is %d\n",*e);
		return TRUE;
}
 
bool GetFront(SqQueue *q,ElemType *e)//取队头元素 
{
	if(q->rear==q->front)
		return FALSE;
	*e=q->Data[q->front];
		printf("GetFront data is %d\n",*e);
	return TRUE;
}
 
int main()
{
	SqQueue FS,*FSPtr;
	FSPtr=&FS;
	ElemType a=1,b=2,c=3;
	ElemType *x=&a;			//用来返回弹出或取出的元素 ,一定要赋初值,否则野指针 
	int i;
 
 
 
    InitQueue(FSPtr);
    printf("%s\n",QueueEmpty(FSPtr)==TRUE?"Queue is Empty":"Queue is not Empty");
    EnQueue(FSPtr,a);
    printf("%s\n",QueueEmpty(FSPtr)==TRUE?"Queue is Empty":"Queue is not Empty");
    EnQueue(FSPtr,b);
    EnQueue(FSPtr,c);
    for(i=0;i<50;i++)  //顺序压0-49数字入队 
    {
    	    EnQueue(FSPtr,i);
   	     					 }
	DeQueue(FSPtr,x);
	printf("DeQueue data is %d\n",*x);
    GetFront(FSPtr,x);

   for(i=0;i<20;i++)  //顺序出队 20次 
    {
    	    DeQueue(FSPtr,x);
    	    	    }
	
	printf("The Queue is:\n");
	
	for(i=(FSPtr->front)%MAXSIZE;i<(FSPtr->rear)%MAXSIZE;i++) //输出全队 
{
	printf("%d	",FSPtr->Data[i]);
}	
getchar();
return 0;
}

猜你喜欢

转载自blog.csdn.net/laguoqing/article/details/84960505