第七周项目2-建立链队算法库
来源:互联网 发布:tensorflow源码语言 编辑:程序博客网 时间:2024/05/22 14:37
问题及代码:
1.头文件:liqueue.h,包含定义链队数据结构的代码、宏定义、要实现算法的函数的声明;
- #ifndef LIQUEUE_H_INCLUDED
- #define LIQUEUE_H_INCLUDED
-
- 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);
-
- #endif // LIQUEUE_H_INCLUDED
2.源文件:liqueue.cpp,包含实现各种算法的函数的定义
- #include <stdio.h>
- #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)
- {
- int n=0;
- QNode *p=q->front;
- while (p!=NULL)
- {
- n++;
- p=p->next;
- }
- return(n);
- }
- 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;
- }
3.在同一项目(project)中建立一个源文件(如main.cpp),编制main函数,完成相关的测试工作。 例:
- #include <stdio.h>
- #include "liqueue.h"
-
- int main()
- {
- ElemType e;
- LiQueue *q;
- printf("(1)初始化链队q\n");
- InitQueue(q);
- printf("(2)依次进链队元素a,b,c\n");
- enQueue(q,'a');
- enQueue(q,'b');
- enQueue(q,'c');
- printf("(3)链队为%s\n",(QueueEmpty(q)?"空":"非空"));
- if (deQueue(q,e)==0)
- printf("队空,不能出队\n");
- else
- printf("(4)出队一个元素%c\n",e);
- printf("(5)链队q的元素个数:%d\n",QueueLength(q));
- printf("(6)依次进链队元素d,e,f\n");
- enQueue(q,'d');
- enQueue(q,'e');
- enQueue(q,'f');
- printf("(7)链队q的元素个数:%d\n",QueueLength(q));
- printf("(8)出链队序列:");
- while (!QueueEmpty(q))
- {
- deQueue(q,e);
- printf("%c ",e);
- }
- printf("\n");
- printf("(9)释放链队\n");
- DestroyQueue(q);
- return 0;
- }
运行结果:
0 0