第七周项目2-建立链队算法库
来源:互联网 发布:苹果5怎么用4g网络 编辑:程序博客网 时间:2024/06/01 08:11
liqueue.h:- typedef char ElemType;
- typedef struct qnode
- {
- ElemType data;
- struct qnode *next;
- } QNode;
- typedef struct
- {
- QNode *front;
- QNode *rear;
- } LiQueue;
- void InitQueue(LiQueue *&q);
- void DestroyQueue(LiQueue *&q);
- bool QueueEmpty(LiQueue *q);
- int QueueLength(LiQueue *q);
- void enQueue(LiQueue *&q,ElemType e);
- bool deQueue(LiQueue *&q,ElemType &e);
liqueue.cpp:- #include <malloc.h>
- #include "liqueue.h"
- void InitQueue(LiQueue *&q)
- {
- q=(LiQueue *)malloc(sizeof(LiQueue));
- q->front=q->rear=NULL;
- }
- void DestroyQueue(LiQueue *&q)
- {
- QNode *p=q->front,*r;
- if(p!=NULL)
- {
- r=p->next;
- while(r!=NULL)
- {
- free(p);
- p=r;
- r=p->next;
- }
- }
- free(p);
- free(q);
- }
- bool QueueEmpty(LiQueue *q)
- {
- return (q->rear==NULL);
- }
- int QueueLength(LiQueue *q)
- {
- QNode *p=q->front;
- int length=0;
- while(p!=NULL)
- {
- length++;
- p=p->next;
- }
- return length;
- }
- void enQueue(LiQueue *&q,ElemType e)
- {
- QNode *p;
- p=(QNode *)malloc(sizeof(QNode));
- p->data=e;
- p->next=NULL;
- if(q->rear==NULL)
- q->front=q->rear=p;
- else
- {
- q->rear->next=p;
- q->rear=p;
- }
- }
- bool deQueue(LiQueue *&q,ElemType &e)
- {
- QNode *t;
- if(q->rear==NULL)
- return false;
- t=q->front;
- if(q->front==q->rear)
- q->front=q->rear=NULL;
- else
- q->front=q->front->next;
- e=t->data;
- free(t);
- return true;
- }
main.cpp:- #include <stdio.h>
- #include <malloc.h>
- #include "liqueue.h"
- int main()
- {
- LiQueue *q;
- ElemType e;
-
- InitQueue(q);
- printf("该队列已被初始化!\n");
-
- if(QueueEmpty(q))
- printf("该队列为空\n");
- else
- printf("该队列不为空\n");
-
- enQueue(q,'a');
- enQueue(q,'b');
- enQueue(q,'c');
-
- printf("元素a,b,c进队后,");
- if(QueueEmpty(q))
- printf("该队列为空\n");
- else
- printf("该队列不为空\n");
-
- if(deQueue(q,e)==0)
- printf("此队列已为空,出队操作失败!\n");
- printf("出队成功,出队元素为%c\n",e);
-
- printf("此时队列中元素个数为:%d\n",QueueLength(q));
-
- enQueue(q,'d');
- enQueue(q,'e');
- enQueue(q,'f');
-
- printf("元素d,e,f进队后,队列中元素个数为:%d\n",QueueLength(q));
-
- printf("出队序列为:");
- while(!QueueEmpty(q))
- {
- deQueue(q,e);
- printf("%c",e);
- }
- printf("\n");
-
- DestroyQueue(q);
- printf("该队列已释放!\n");
-
- return 0;
- }
运行结果: 0 0