队列的实现

队列的实现

typedef int SDATA;
typedef struct Queue//节点
{
	struct Queue* next;
	SDATA data;
}Qnode;
typedef struct Chmpas//队头、队位
{
	Qnode* front;
	Qnode* rear;
}queue;

 
void InitQueue(queue* pt);//初始化
void PushQueue(queue* pt, SDATA x);//入队
void PopQueue(queue* pt);//出队
SDATA FrontData(queue* pt);//头部数据
SDATA RearData(queue* pt);//尾部数据
void DestroyQueue(queue* pt);//释放空间
int QueueSize(queue* pt);//队列数据

void InitQueue(queue* pt)
{
	assert(pt);
	pt->front = pt->rear = NULL;
}
void PushQueue(queue* pt, SDATA x)
{
	assert(pt);
	Qnode* newnode = (Qnode*)malloc(sizeof(Qnode));//开辟节点
	if(newnode == NULL)
	{
		printf("malloc fail\n");
		return;
	}
	newnode->data = x;
	newnode->next = NULL;
	if (pt->front == NULL)
	{
		pt->front = pt->rear = newnode;
	}
	else
	{
		pt->rear->next = newnode;
		Qnode* tp = pt->rear->next;
		pt->rear = tp;
	}
}

void PopQueue(queue* pt)//出队
{
	assert(pt);
	if (pt->front->next == NULL)//单个节点情况
	{
		free(pt->front);
		pt->front = pt->rear = NULL;
	}
	Qnode* next = pt->front->next;//先临时保存再释放
	free(pt->front);
	pt->front = next;
}
SDATA FrontData(queue* pt)//头部数据
{
	assert(pt);
	assert(pt->front);
	return pt->front->data;
}
SDATA RearData(queue* pt)//尾部数据
{
	assert(pt);
	assert(pt->rear);
	return pt->rear->data;
}
void DestroyQueue(queue* pt)//释放
{
	assert(pt);
	Qnode* cur = pt->front->next;
	while (cur)
	{
		Qnode* next = cur->next;
		free(cur);
		cur = next;
	}
	pt->front = pt->rear = NULL;
}
int QueueSize(queue* pt)//计算个数
{
	assert(pt);
	int count = 0;
	Qnode* cur = pt->front;//依旧采用循环方式
	while (cur)
	{
		cur = cur->next;
		cur++;
	}
	return count;
}
bool QueueEmpty(queue* pt)//布尔判断
{
	assert(pt);
	return pt->front == NULL;
}
  • 7
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值