链式队列


链式队列的初始化、销毁、入队、出队操作,测试用例为:将0~19入队,并打印输出结果




typedef int QElemType;
typedef struct QNode
{
	QElemType data;
	struct QNode *next;
}QNode, *QueuePtr;

typedef struct
{
	QueuePtr front;
	QueuePtr rear;
}LinkQueue;

/* 构造一个空的队列Q */
bool InitQueue(LinkQueue &Q)
{
	Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
	if (!Q.front)
	{
		printf("链队列创建失败!\n");
		exit(1);
	}
	Q.front->next = NULL;
	return TRUE;
}

/* 销毁队列 */
bool Destroy(LinkQueue &Q)
{
	while (Q.front)
	{
		Q.rear = Q.front->next;
		free(Q.front);
		Q.front = Q.rear;
	}
	return TRUE;
}

/* 插入元素 */
bool EnQueue(LinkQueue &Q, QElemType e)
{
	QNode *p = (QueuePtr)malloc(sizeof(QNode));
	if (!p) exit(1);
	p->data = e;
	Q.rear->next = p;
	p->next = NULL;
	Q.rear = p;

	return TRUE;
}

/* 删除元素 */
bool DeQueue(LinkQueue &Q, QElemType &e)
{
	if (Q.front == Q.rear) return FALSE;
	QNode *p;
	p = Q.front->next;
	e = p->data;
	Q.front->next = p->next;
	if (Q.rear == p) Q.rear = Q.front;
	free(p);
	return TRUE;
}

int main()
{
	LinkQueue Q;
	InitQueue(Q);
	printf("输入的链队列!\n");
	for (int i=0; i<20; ++i)
	{
		EnQueue(Q, i);
		printf(" %d ",i);
	}
	printf("\n输出链队列元素!\n");
	QElemType temp;
	for (int i=0; i<20; ++i)
	{
		DeQueue(Q, temp);
		printf(" %d ", temp);
	}
	printf("\n");
	Destroy(Q);
	system("pause");
	return 0;
}












评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值