链式队列的实现

目录

一、队列的结构定义

二、队列的初始化

三、队列的打印

四、入队

五、出队

六、取队头元素

七、取队尾元素

八、判断队列是否为空

九、求队列大小

十、销毁队列

十一、测试代码


一、队列的结构定义

//队列的结构定义
typedef int QDataType;

typedef struct QueueNode {
	QDataType val;
	struct QueueNode* next;
}QNode;

//将头指针和尾指针存放到一个结构体中组成队列,易于找到队列头和尾且无需使用二级指针
typedef struct QueueNode {
	QNode* phead;
	QNode* ptail;
	int size;
}Queue;

二、队列的初始化

//队列的初始化
void QueueInit(Queue* pq)
{
	assert(pq);
	pq->phead = pq->ptail = NULL;
	pq->size = 0;
}

三、队列的打印

//队列的打印
void QueuePrint(Queue* pq)
{
	assert(pq);
	if (pq->phead == NULL)
		printf("NULL\n");
	else
	{
		QNode *cur = pq->phead;
		while (cur)
		{
			printf("%d ", cur->val);
		}
		printf("\n");
	}
}

四、入队

//入队列
void QueuePush(Queue* pq, QDataType x)
{
	assert(pq);
	QNode* newnode = (QNode*)malloc(sizeof(QNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	newnode->val = x;
	newnode->next = NULL;
	if (pq->phead == NULL)
	{
		pq->phead = pq->ptail = newnode;
	}
	else
	{
		pq->ptail->next = newnode;
		pq->ptail = newnode;
	}
	pq->size++;
} 

五、出队

//出队列
void QueuePop(Queue* pq)
{
	assert(pq);
	assert(pq->ptail);
	if (pq->phead == pq->ptail)//队列中只有一个元素
	{
		pq->ptail = NULL;
	}
	QNode* tmp = pq->phead;
	pq->phead = pq->phead->next;
	free(tmp);
	tmp = NULL;

	pq->size--;
}

六、取队头元素

//取队头元素
QDataType QueueFront(Queue* pq)
{
	assert(pq);
	assert(pq->phead);//空队列

	return pq->phead->val;
}

七、取队尾元素

//取队尾元素
QDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(pq->ptail);//空队列

	return pq->ptail->val;
}

八、判断队列是否为空

//判断队列是否为空
bool QueueEmpty(Queue* pq)
{
	return pq->phead == NULL;
}

九、求队列大小

//求队列大小
int QueueSize(Queue* pq)
{
	assert(pq);
	return pq->size;
}

十、销毁队列

//销毁队列
void QueueDestroy(Queue* pq)
{
	assert(pq);
	QNode* cur = pq->phead;
	while (cur)
	{
		QNode* tmp = cur;
		cur = cur->next;
		free(tmp);
		tmp = NULL;
	}
	pq->phead = NULL;
	pq->ptail = NULL;
	pq->size = 0;
}

十一、测试代码

void test01()
{
    //定义一个队列
    Queue q;
    //初始化队列
    QueueInit(&q);
    //入队
    QueuePush(&q, 1);
    QueuePush(&q, 2);
    QueuePush(&q, 3);
    QueuePush(&q, 4);
    QueuePush(&q, 5);
    //队列打印
    QueuePrint(&q);
    //出队列
    QueuePop(&q);
    QueuePop(&q);
    QueuePop(&q);
    //队列打印
    QueuePrint(&q);
    //取队头元素
    printf("%d\n", QueueFront(&q));
    //取队尾元素
    printf("%d\n", QueueBack(&q));
    //判断队列是否为空
    if (QueueEmpty(&q))
        printf("空\n");
    else
        printf("非空\n");
    //求队列大小
    printf("%d\n", QueueSize(&q));
    //销毁队列
    QueueDestroy(&q);
}

int main()
{
    test01();
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南林yan

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值