循環キューの基本操作と実現


#include "stdio.h"
#include  "stdlib.h"
#define TRUE 1
#define ERROR 0
#define OK 1
#define FALSE 0
#define OVERFLOW -1

typedef int QElemType;
typedef int Status;
#define MAXQSIZE 100
typedef struct  
{
	QElemType *base;
	int front;
	int rear;
}SqQueue;

//        
Status InitSqQueue(SqQueue *Q){
	Q->base=(QElemType*)malloc(MAXQSIZE*sizeof(QElemType));
	if(!Q->base) exit (OVERFLOW);
	Q->front=Q->rear=0;
	return OK;
}

//     
int LengthSqQueue(SqQueue Q)
{
	return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}

//      (      )
Status EnSqQueue(SqQueue *Q,QElemType e){
	if((Q->rear+1)%MAXQSIZE==Q->front) return ERROR;
	Q->base[Q->rear]=e;
	Q->rear=(Q->rear+1)%MAXQSIZE;
	return OK;
}

//      (      )
Status DeSqQueue(SqQueue *Q,QElemType *e){
	if(Q->front==Q->rear) return ERROR;
	e=Q->base[Q->front];
	Q->front=(Q->front+1)%MAXQSIZE;
	return OK;
}

//    
Status EmptySqQueue(SqQueue Q)
{ 
	if(Q.front==Q.rear) 
		return TRUE;
	else 
		return FALSE;
}

//        (      e      )
Status Getfront(SqQueue *Q,QElemType *e)
{ 
	if(Q->front==Q->rear)
		return ERROR;
	else
	*e=Q->base[Q->front];              
		return OK;
}

//    
Status DestroySqQueue(SqQueue Q)
{
	while ( Q.front!= Q.rear)
	{
	  free(&Q.base[Q.front]);
	  Q.front=(Q.front+1)%MAXQSIZE;
	}
	return OK;
}

//      
Status  ClearSqQueue(SqQueue Q)
{  
	int i=Q.front;
	while (i != Q.rear)
	   {
	   i=0;
	   i++;
	   }
	   Q.front=Q.rear=0;
}

//  
void PrintSqQueue (SqQueue Q)
{ 
	int i;
	i=Q.front;
	while(i!=Q.rear)
	  { 
		printf("%d\t",Q.base[i]);
		i=(i+1)%MAXQSIZE;
	  }
	  printf("
"); } void main() { SqQueue Q; int choice=1; if(InitSqQueue(&Q)==OK) printf("InitSqQueue success! "); else printf("InitSqQueue fail!"); while(choice!=0) { system("cls"); printf("*********************************************************
"); printf(" 1.SqQueueEmpty 2.SqQueueLength 3.SqQueueClear 4.DeQueue
"); printf(" 5.SqQueuePrint 6.EnQueue 7.SqQueueDestroy 8.Getfront
"); printf(" 0.Exit
"); printf("*********************************************************
"); printf("please input your choice:"); scanf("%d",&choice); switch(choice) { case 0: system("cls"); printf("Bye Bye!
"); break; case 1: if(EmptySqQueue(Q)==TRUE) printf("The Queue is empty!
"); else printf("The Queue is not empty!
"); break; case 2: printf("The QueueLength is %d
",LengthSqQueue(Q)); break; case 3: if(ClearSqQueue(Q)==OK) printf("The Queue is Cleared!"); else printf("The Queue is not Cleared!"); break; case 4: { QElemType e; if(DeSqQueue(&Q,&e)==OK) { printf(" !
"); printf(" :
"); PrintSqQueue(Q); } break; } case 5: PrintSqQueue(Q); break; case 6: { QElemType e; printf("
"); scanf("%d",&e); if(EnSqQueue(&Q,e)==OK) { printf(" !
"); printf(" :
"); PrintSqQueue(Q); } break; } case 7: if(DestroySqQueue(Q)==TRUE) printf("The Queue is Destroyed !
"); else printf("The Queue is not Destroyed!
"); break; case 8: { QElemType e; if(Getfront(&Q,&e)==OK) printf(" :%d
",e); break; } default: break; } system("pause"); } }