上篇讲到了栈,这一集我们来讲队列— 。—
队列概念
顾名思义,队列就相当于排队一样,先进先出,只允许在一段进行数据插入,只准在一段进行数据出队,插入的地方我们称作队尾,出队的地方称作队头
如何实现
我们可以用顺序表和链表去实现队列,我们在这里选择链表,因为如果要使用顺序表实现,在出数据时,效率则会大打折扣
链表实现大体结构如下
插入则直接尾插,出队则出队头即可
队列实现
队列结构架构——头文件
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <stdbool.h>
#include <errno.h>
#include <assert.h>
typedef int QDataType;
// 链式结构:表示队列
typedef struct QListNode
{
struct QListNode* _next;
QDataType _data;
}QNode;
这是一个队列中一个节点的结构,在实际队列中,我们因为会时刻访问队列头和尾,还需要记录整个队列的长度,为防止使用二级指针,我们可以再包一层,实现队列的结构
// 队列的结构
typedef struct Queue
{
int size;//队列长度
QNode* _head;
QNode* _tail;
}Queue;
各类接口
// 初始化队列
void QueueInit(Queue* q);
// 队尾入队列
void QueuePush(Queue* q, QDataType data);
// 队头出队列
void QueuePop(Queue* q);
// 获取队列头部元素
QDataType QueueFront(Queue* q);
// 获取队列队尾元素
QDataType QueueBack(Queue* q);
// 获取队列中有效元素个数
int QueueSize(Queue* q);
// 检测队列是否为空,如果为空返回非零结果,如果非空返回0
int QueueEmpty(Queue* q);
// 销毁队列
void QueueDestroy(Queue* q);
//打印数据
QDataType QueuePrint(Queue* q);
初始化队列
void QueueInit(Queue* q) {
assert(q);
q->_head = q->_tail = NULL;
q->size = 0;
}
入队列
// 入队列
void QueuePush(Queue* q, QDataType data) {
assert(q);
QNode* newnode = (QNode*)malloc(sizeof(QNode));
if (newnode==NULL)
{
perror("newnode malloc error");
return -1;
}
newnode->_data = data;
newnode->_next = NULL;
if (q->_tail==NULL)
{
q->_head = q->_tail = newnode;
}
else
{
q->_tail->_next = newnode;
q->_tail = newnode;
}
q->size++;
}
在这里也不需要额外写一个创建节点开辟空间的函数,因为这里只会在这开辟空间,
出队列
void QueuePop(Queue* q) {
assert(q);
assert(q->_head);
QNode* del = q->_head;
q->_head = q->_head->_next;
free(del);
del = NULL;
if (q->_head == NULL) {
q->_tail = NULL;
}
q->size--;
}
由于是链表实现,则需要以链表形式删除数据
获取队列头部元素
QDataType QueueBack(Queue* q) {
assert(q);
assert(q->_tail);
return q->_tail->_data;
}
获取队列中有效元素个数
int QueueSize(Queue* q) {
assert(q);
Queue* cur=q;
int count = 0;
while (cur->_head != NULL)
{
count++;
cur->_head = cur->_head->_next;
}
return count;
}
打印队列元素
void QueuePrint(Queue* q) {
assert(q);
Queue* cur = q;
while (cur->_head!=NULL)
{
printf("%d—",cur->_head->_data);
cur->_head = cur->_head->_next;
}
}
遍历打印即可
检查队列是否为空
bool QueueEmpty(Queue* q) {
assert(q);
return q->_head == NULL;
}
销毁队列
void QueueDestroy(Queue* q) {
assert(q);
QNode* cur = q->_head;
while (cur)
{
QNode* next = cur->_next;
free(cur);
cur = next;
}
}