#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define MAXSIZE 5
#define OVERFLOW -1
#define OK 1
#define TRUE 1
#define FALSE 0
#define ERROR 1
typedef int QElemType;
typedef int Status;
struct SqQueue
{
QElemType *base;
int front;
int rear;
};
Status InitQueue(SqQueue &Q)
{
Q.base = (QElemType *)malloc(MAXSIZE * sizeof(QElemType));
if(!Q.base)
exit(OVERFLOW);
Q.front = Q.rear = 0;
return OK;
}
Status DestoryQueue(SqQueue &Q)
{
if(Q.base)
free(Q.base);
Q.base = NULL;
Q.front = Q.rear = 0;
return OK;
}
Status ClearQueue(SqQueue &Q)
{
Q.front = Q.rear = 0;
return OK;
}
Status QueueEmpty(SqQueue Q)
{
if(Q.front == Q.rear)
return TRUE;
else
return FALSE;
}
int QueueLength(SqQueue Q)
{
return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}
Status GetHead(SqQueue Q, QElemType &d)
{
if(Q.front == Q.rear) return ERROR;
d = *(Q.base + Q.front);
return OK;
}
Status EnQueue(SqQueue &Q,QElemType e)
{
if((Q.rear + 1)%MAXSIZE == Q.front)
return TRUE;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1)%MAXSIZE;
return OK;
}
Status DeQueue(SqQueue &Q,QElemType &e)
{
if(Q.front == Q.rear)
return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1)%MAXSIZE;
return OK;
}
Status QueueTraverse(SqQueue Q, void(*visit)(QElemType))
{
int i;
i = Q.front;
while(i != Q.rear)
{
visit(Q.base[i]);
i = (i+1)%MAXSIZE;
}
printf("\n");
return OK;
}
void visit(QElemType e)
{
printf("%d ",e);
}
int main()
{
int i = 0,l;
Status j;
QElemType d;
SqQueue Q;
InitQueue(Q);
printf("After init queue,is it empty?%d(1:YES 0:NO)\n",QueueEmpty(Q));
printf("Please input int type queue (length is less than %d), -1 is end character:\n",MAXSIZE - 1);
do
{
scanf("%d",&d);
++i;
if(d == -1)
break;
EnQueue(Q,d);
}while(i < MAXSIZE -1);
printf("The length of queue is:%d\n",QueueLength(Q));
printf("Is it empty?%d(1:YES 0:NO)\n",QueueEmpty(Q));
printf("Delete element % times from the head of queue, insert element at the end of queue:\n",MAXSIZE);
for(i = 0; i < MAXSIZE; ++i)
{
DeQueue(Q,d);
printf("The deleted element is %d,please input the new element:\n",d);
scanf("%d",&d);
EnQueue(Q,d);
}
l = QueueLength(Q);
printf("The elements of queue are:\n");
QueueTraverse(Q,visit);
printf("the number of inserted data at end of queue is:%d\n", i+MAXSIZE);
if(l - 2 > 0)
printf("delete %d elements:\n",l-2);
while(QueueLength(Q) > 2)
{
DeQueue(Q,d);
printf("the deleted element is:%d\n",d);
}
j = GetHead(Q,d);
if(j)
printf("the head element is:%d\n",d);
ClearQueue(Q);
printf("After clear queue,is it empty?(1:YES 0:NO)\n",QueueEmpty(Q));
DestoryQueue(Q);
return 0;
}
顺序循环队列基本操作(入队,出队,清空,销毁,历遍)
最新推荐文章于 2024-08-14 21:43:03 发布