链式队列的实现

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
#include<string.h>

typedef int ElemType;
typedef struct Node
{
	ElemType data;
	struct Node* next;
}QueueNode;
typedef struct Head
{
	struct Node* front;
	struct Node* rear;
	int cursize;
}QueueHead;
QueueNode* BuyNode()
{
	QueueNode* s = (QueueNode*)malloc(sizeof(QueueNode));
	if (nullptr == s) exit(1);
	memset(s, 0, sizeof(QueueNode));
	return s;
}
void Init_Queue(QueueHead* phead)
{
	assert(phead != nullptr);
	memset(phead, 0, 12);
}
bool Push_Back(QueueHead* phead, ElemType val)
{
	assert(phead != nullptr);
	QueueNode* pnewnode = BuyNode();
	pnewnode->data = val;
	if (nullptr == phead->front)
	{
		phead->front = pnewnode;
		phead->rear = pnewnode;
		phead->cursize += 1;
	}
	else
	{
		phead->rear->next = pnewnode;
		phead->rear = pnewnode;
		phead->cursize += 1;
	}
	return true;
}
bool Is_Empty(QueueHead* phead)
{
	assert(phead != nullptr);
	return phead->front == nullptr;
}
bool Pop_Front(QueueHead* phead, ElemType& val)
{
	assert(phead != nullptr);
	if (Is_Empty(phead)) exit(1);
	if (nullptr == phead->front->next)
	{
		val = phead->front->data;
		free(phead->front);
		phead->front = nullptr;
		phead->rear = nullptr;
		phead->cursize -= 1;
	}
	else
	{
		QueueNode* q = phead->front;
		val = q->data;
		phead->front = q->next;
		free(q);
		q = nullptr;
		phead->cursize -= 1;
	}
}
int Get_Length(QueueHead* phead)
{
	assert(phead != nullptr);
	return phead->cursize;
}
void Print_Queue(QueueHead* phead)
{
	assert(phead != nullptr);
	QueueNode* p = phead->front;
	while (p != nullptr)
	{
		printf("%3d", p->data);
		p = p->next;
	}
	printf("\n");
}
void Clear_Queue(QueueHead* phead)
{
	assert(phead != nullptr);
	int n = 0;
	while (phead->front != nullptr)
	{
		Pop_Front(phead, n);
	}
}
int main()
{
	QueueHead myhead;
	Init_Queue(&myhead);
	for (int i = 0; i < 10; ++i)
	{
		Push_Back(&myhead, i);
	}
	Print_Queue(&myhead);
	printf(" Lenget=%d\n", Get_Length(&myhead));
	int n = 0;
	Pop_Front(&myhead, n);
	Print_Queue(&myhead);
	printf(" Length=%d\n", Get_Length(&myhead));
	Clear_Queue(&myhead);
	Print_Queue(&myhead);
	printf(" Length=%d\n", Get_Length(&myhead));
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值