#include<stdio.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW 02
typedef int QElemtype;
typedef int Status;
//Storage structure
typedef struct QNode
{
QElemtype data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front ; //头指针
QueuePtr rear; //尾指针
}LinkQueue;
//初始化队列
Status InitQueue(LinkQueue *Q)
{
Q->front=Q->rear=(QNode *)malloc(sizeof(QNode));
if(!Q->front)
{
exit(OVERFLOW);
}
Q->front->next=NULL;
return OK;
}
//销毁队列
Status DestroyQueue(LinkQueue *Q) //此时的Q.rear 只是辅助的指针 失去了它原来的意义
{
while(Q->front)
{
Q->rear=Q->front->next;
free(Q->front);
Q->front=Q->rear;
}
return OK;
}
//清空队列
Status ClearQueue(LinkQueue *Q)
{
DestroyQueue(Q);
InitQueue(Q);
}
//判断队列是否为空
Status isEmpty(LinkQueue Q)
{
if(Q.front->next==NULL)
{
return TRUE;
}
else
{
return FALSE;
}
}
Status GetLength(LinkQueue Q)
{
int i=0;
QueuePtr p=Q.front;
while(Q.rear!=p) //是否还可以通过p=Q.front->next; while(!p){ i++;p=p->next;}
{
i++;
p=p->next;
}
return i;
}
//获取队首元素
Status GetHead(LinkQueue Q,QElemtype *e)
{
QueuePtr p;
if(Q.front==Q.rear)
{
return ERROR;
}
p=Q.front->next;
*e=p->data;
return OK;
}
//入队
Status EnQueue(LinkQueue *Q,QElemtype e)
{
QueuePtr p=(QNode *)malloc(sizeof(QNode));
if(!p)
{
exit(OVERFLOW);
}
p->data=e;
p->next=NULL;
Q->rear->next=p; //使上一次的队尾的next 指向现在的队尾元素
Q->rear=p; //rear指向新的队尾元素
return OK;
}
//出队
Status DeQueue(LinkQueue *Q,QElemtype *e)
{
QueuePtr p;
if(Q->front==Q->rear)
{
return ERROR;
}
p=Q->front->next;
*e=p->data;
Q->front->next=p->next;
if(Q->rear==p)
{
Q->rear=Q->front;
}
free(p);
return OK;
}
//遍历队列
Status TraverseQueue(LinkQueue Q)
{
if(Q.front==Q.rear)
{
printf("The queue is empty\n");
return ERROR;
}
else
{
QueuePtr p=Q.front->next;
printf("Traverse sequence as follows:\n");
while(p)
{
printf("%3d",p->data);
p=p->next;
}
return OK;
}
}
int main()
{
LinkQueue Q;
if(InitQueue(&Q))
{
QElemtype e;
int i;
printf("init_success\n");
if(isEmpty(Q))
{
printf("queue is empty\n");
}
for(i=0;i<10;i++)
{
EnQueue(&Q,i+1);
}
GetHead(Q,&e);
printf("The first element is %d\n",e);
printf("The length of the queue is %d\n",GetLength(Q));
DeQueue(&Q,&e);
printf("delete element is %d\n",e);
TraverseQueue(Q);
if(DestroyQueue(&Q))
{
printf("\ndestroy success\n");
}
TraverseQueue(Q);
}
return 0;
}