下面是按严蔚敏书第65页上要求写的数据结构里的队列的一些基本操作,在codeblocks10.5中测试正确,C语言实现:
#include <stdio.h>
#include <stdlib.h>
#define MAXQSIZE 100
#define OK 1
#define ERROR 0
typedef int Status;
typedef int QElemType;
typedef struct {
QElemType *base;
int front;
int rear;
}SqQueue;
Status InitQueue(SqQueue *Q)
{
Q->base = (QElemType *)malloc(MAXQSIZE * sizeof(QElemType));
if (!Q->base)
{
exit(ERROR);
}
Q->front = Q->rear = 0;
return OK;
}
int QueueLength(SqQueue *Q)
{
return (Q->rear - Q->front + MAXQSIZE) % MAXQSIZE;
}
void EnQueue(SqQueue *Q,QElemType e)
{
if ((Q->rear + 1) % MAXQSIZE == Q->front) //队列满
return ;
Q->base[Q->rear] = e;
printf("%d has enqueued\n",e);
Q->rear = (Q->rear + 1) % MAXQSIZE;
}
int DeQueue(SqQueue *Q)
{
int e;
if (Q->front == Q->rear) //队列空
return ERROR;
e = Q->base[Q->front];
Q->front = (Q->front +1) % MAXQSIZE;
return e;
}
/*
void printQueue(SqQueue *Q)
{
SqQueue *p = Q;
if (p->front == p->rear)
printf("Queue is empty!\n");
printf("Queue has elements:\n");
while (p->front != p->rear)
{
printf("%d\t",p->base[p->front]);
p->front = (p->front + 1) % MAXQSIZE;
}
printf("\n");
}
*/
int main()
{
int length,e;
SqQueue Q; //定义队列
if(InitQueue(&Q)) //初始化
printf("Init Success!\n");
length = QueueLength(&Q); //队列长度
printf("Length is %d\n", length);
EnQueue(&Q,3); //入队
EnQueue(&Q,4);
//printQueue(&Q);
length = QueueLength(&Q); //队列长度
printf("Length is %d\n", length);
e = DeQueue(&Q);//出队
printf("Delete is %d\n",e);
return 0;
}