网站建设平台 三合一seo排名快速上升
1.队列的概念
队列:只允许在一端进行插入数据操作,在另一端进行删除数据操作的特殊线性表,队列具有先进先出FIFO(First In First Out)。入队列:进行插入操作的一端称为队尾 出队列:进行删除操作的一端称为队头
2.队列的实现
1.初始化
2.销毁
3.队尾入队列
4.队头出队列
5.获取队列头部元素
6.获取队列尾部元素
7.有效元素个数
8.判是否为空
typedef int QDataType; //链式结构表示队列 typedef struct QListNode {struct QListNode* pNext;QDataType data; }QNode; //队列的结构 typedef struct Queue {QNode* phead;QNode* ptail;int size; }Queue;
2.1 初始化与销毁
void QueueInit(Queue* pq) {assert(pq);pq->phead = NULL;pq->ptail = NULL;pq->size = 0; } void QueueDestroy(Queue* pq) {assert(pq);QNode* cur = pq->phead;while (cur){QNode* next = cur->next;free(cur);cur = next;}pq->phead = NULL;pq->ptail = NULL;pq->size = 0; }
2.2 队尾入队列与队头出队列
//队尾入队列 void QueuePush(Queue* pq, QDataType x) {assert(pq);QNode* newnode = (QNode*)malloc(sizeof(QNode));if (newnode == NULL){perror("malloc fail\n");return;}newnode->data = x;newnode->next = NULL;if (pq->phead == NULL){assert(pq->ptail == NULL);pq->phead = pq->ptail = newnode;}else{pq->ptail->next = newnode;pq->ptail = newnode;}pq->size++; } //队头出队列 void QueuePop(Queue* pq) {assert(pq);assert(!QueueEmpty(pq));//分类讨论//1.一个节点 2.两个节点if (pq->phead->next == NULL){free(pq->phead);pq->phead = NULL;pq->ptail = NULL;}else{QNode* next = pq->phead->next;free(pq->phead);pq->phead = next;}pq->size--; }
2.3 获取队列头部元素与获取队列尾部元素
//获取队列头部元素 QDataType QueueFront(Queue* pq) {assert(pq);assert(!QueueEmpty(pq));return pq->phead->data; } //获取队列尾部元素 QDataType QueueBack(Queue* pq) {assert(pq);assert(!QueueEmpty(pq));return pq->ptail->data; }
2.4 有效元素个数与判是否为空
//有效元素个数 int QueueSize(Queue* pq) {assert(pq);return pq->size; } //判断队列是否为空,如果为空返回非零结果,如果非空返回0 bool QueueEmpty(Queue* pq) {assert(pq);return pq->size == 0; }