链队列的初始化、出队、入队、取队头元素、判空

#include<iostream>
#include<malloc.h>
using namespace std;

typedef struct qnode
{
	int data;
	struct qnode *next;
}LQNode;
typedef struct
{
	LQNode *front;   //队头
	LQNode *rear;    //队尾
}LQueue;
void QueueInitiate(LQueue *q)   //初始化
{
	q->front = NULL;
	q->rear = NULL;
}
int QueueNotEmply(LQueue q)   //判空
{
	if (q.front == NULL)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}
void QueueAppend(LQueue *q, int x)    //入队列
{
	LQNode *p;
	p = (LQNode *)malloc(sizeof(LQNode));
	p->data = x;
	p->next = NULL;
	if (q->rear != NULL)   //队列非空时
	{
		q->rear->next = p;
	}
	q->rear = p;
	if (q->front == NULL)  //队列为空时
	{
		q->front = p;
	}
}
int QueueDelete(LQueue *q, int *x)  //出队列
{
	LQNode *p;
	if (q->front == NULL)
	{
		printf("队列为空,无数据元素出队列!\n");
		return 0;
	}
	else
	{
		*x = q->front->data;
		p = q->front;
		q->front = q->front->next;
		if (q->front == NULL)  
		{
			q->rear = NULL;
		}
		free(p);
		return 1;
	}
}
int QueueGet(LQueue q, int *x)  //取队头数据元素
{
	if (q.front == NULL)
	{
		printf("队列为空,无数据元素可取!\n");
		return 0;
	}
	else
	{
		*x = q.front->data;
		return 1;
	}
}
int main()
{
	LQueue q;
	int i, x;
	QueueInitiate(&q);
	for (i = 0; i < 10; i++)
	{
		QueueAppend(&q,i+1);
	}
	QueueGet(q, &x);
	printf("取队头数据元素:%d \n",x);
	printf("依次删除队头数据元素序列:");
	while (QueueNotEmply(q))
	{
		QueueDelete(&q,&x);
		printf("%d  ",x);
	}
	printf("\n");
	return 0;
}

  • 8
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值