数据结构之链队列的实现

来源:互联网 发布:建网站做淘宝客 编辑:程序博客网 时间:2024/05/22 02:49
/**********************链队列********************/#include"stdio.h"#include"stdlib.h"#define ERROR 0#define OK 1#define FALSE 0#define TRUE 1typedef int ElemType;typedef int Status;typedef struct QNode{ElemType data;struct QNode *next;}QNode,*QueuePtr;typedef struct{QueuePtr front,rear;}LinkQueue;/*********************Operator***************/void InitQueue(LinkQueue *Q)//初始化队列{Q->front=Q->rear=NULL;}void ClearQueue(LinkQueue *Q)//清空队列{QueuePtr p;while(Q->front!=Q->rear){p=Q->front->next;Q->front->next=p->next;if(p==Q->rear)//当删除的是最后一个元素时,令头尾指针指向相同Q->rear=Q->front;free(p);}if(Q->front)free(Q->front);}void DestroyQueue(LinkQueue *Q)//销毁队列{ClearQueue(Q);free(Q);}Status EmptyQueue(LinkQueue Q)//判断队列是否为空{if(Q.front==NULL&&Q.rear==NULL)return TRUE;return FALSE;}int QueueLength(LinkQueue Q)//返回队列的长度{int count=0;QueuePtr p;while(Q.front!=Q.rear){p=Q.front;Q.front=p->next;count++;}return count;}Status EnQueue(LinkQueue *Q, ElemType e)//入队操作{QueuePtr p;p=(QueuePtr)malloc(sizeof(QNode));if(!p)exit(ERROR);p->data=e;p->next=NULL;if(EmptyQueue(*Q))//让front与rear同时指向第一个结点Q->front=Q->rear=p;else{Q->rear->next=p;Q->rear=p;}return OK;}Status DeQueue(LinkQueue *Q,ElemType *e)//出队操作,将队头元素返回给e{QueuePtr p;if(EmptyQueue(*Q))return ERROR;p=Q->front->next;*e=p->data;Q->front->next=p->next;if(p==Q->rear)//当删除的是最后一个元素时,令头尾指针指向相同Q->rear=Q->front;free(p);return OK;}void PrintQueue(LinkQueue Q)//打印队列{QueuePtr p;p=Q.front;do{   printf("%6d",p->data);p=p->next;}while(p!=Q.rear->next);printf("\n");}main(void){LinkQueue *Q;ElemType *e;Q=(LinkQueue*)malloc(sizeof(LinkQueue));e=(ElemType*)malloc(sizeof(ElemType));InitQueue(Q);EnQueue(Q,12);EnQueue(Q,13);EnQueue(Q,14);EnQueue(Q,15);EnQueue(Q,16);EnQueue(Q,17);printf("hello\n");PrintQueue(*Q);DeQueue(Q,e);PrintQueue(*Q);printf("%6d\n",*e);ClearQueue(Q);printf("asid\n");PrintQueue(*Q);//运行时此处为空链表 输出为随机地址printf("asid\n");}


                                             
0 0
原创粉丝点击