实现的基本函数有:
- 申请一个节点:QNode *BuyNode()
- 释放一个节点:void FreeNode(QNode *p)
- 初始化队列:void InitQueue(LiQueue &lqu)
- 清除队列:void Clear(LiQueue &lqu)
- 摧毁队列:void DestroyQueue(LiQueue &lqu)
- 判断队列是否为空:bool QueueEmpty(LiQueue &lqu)
- 元素节点入队:bool Push(LiQueue &lqu, ElemType x)
- 元素节点出队:bool Pop(LiQueue &lqu, ElemType &x)
- 获得队头元素:ElemType GetFront(LiQueue &lqu)
- 获得队尾元素:ElemType GetRear(LiQueue &lqu)
- 输出该队列:void Print(LiQueue &lqu)
#include<stdlib.h> #include<assert.h> #include<string.h> #include<stdio.h> typedef int ElemType; typedef struct qnode { ElemType data; qnode *next; }QNode; //声明链队数据节点类型、节点类型指针类型 typedef struct { QNode *front; QNode *rear; int cursize; }LiQueue; //声明链队类型 QNode *BuyNode() { QNode *p = (QNode *)malloc(sizeof(QNode)); if (p == NULL)exit(1); memset(p, 0, sizeof(QNode)); return p; } void FreeNode(QNode *p) { free(p); p = NULL; } void InitQueue(LiQueue &lqu) //初始化链队 { lqu.cursize = 0; lqu.front = lqu.rear = BuyNode(); } void Clear(LiQueue &lqu) //清空链队 { QNode *p = NULL; while (lqu.front->next != NULL) { p = lqu.front->next; lqu.front->next = p->next; FreeNode(p); } lqu.rear = lqu.front; lqu.cursize = 0; } void DestroyQueue(LiQueue &lqu) //摧毁链队 { Clear(lqu); FreeNode(lqu.front); lqu.rear = NULL; } bool QueueEmpty(LiQueue &lqu) //判断链队是否为空 { return lqu.cursize==0; } bool Push(LiQueue &lqu, ElemType x) //元素入队 { QNode *p = BuyNode(); p->data = x; p->next = NULL; lqu.rear->next = p; lqu.rear = p; lqu.cursize += 1; return true; } bool Pop(LiQueue &lqu, ElemType &x) //元素出队 { if (QueueEmpty(lqu)) return false; QNode *p=lqu.front->next; x = p->data; lqu.front->next = p->next; free(p); lqu.cursize -= 1; if (lqu.cursize == 0) { lqu.rear = lqu.front; } return true; } ElemType GetFront(LiQueue &lqu) //获得队头元素 { assert(!QueueEmpty(lqu)); return lqu.front->data; } ElemType GetRear(LiQueue &lqu) //获得队尾元素 { assert(!QueueEmpty(lqu)); return lqu.rear->data; } void Print(LiQueue &lqu) //打印输出队列 { QNode *p = lqu.front; while (p != NULL) { printf("% d ", p->data); p = p->next; } } int main() { int arr[] = { 12,34,34,45,56,78,89 }; int n = sizeof(arr) / sizeof(arr[0]); LiQueue myLiQueue; InitQueue(myLiQueue); for (int i = 0; i < n; i++) { Push(myLiQueue, arr[i]); } for (int i = 0; i < n; i++) { int x; Pop(myLiQueue, x); printf("%d ", x); } DestroyQueue(myLiQueue); return 0; }
本程序在VS2017运行通过