九、数据结构之队列的链队列的存储结构

代码的具体实现请参考第二个文章的单链表存储结构和第八章的循环队列存储结构,实现思想近似

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

#define OK 1
#define ERROR 0

typedef int Status;
typedef int ElemType;

typedef struct QueueNode
{
	ElemType data;
	struct QueueNode *next;
}QueueNode; 

typedef QueueNode *QueueLink;

typedef struct
{
	QueueLink front;
	QueueLink rear;	
	int length;
}Queue; 

//初始化
Status Init(Queue *q)
{
	QueueLink qNode = (QueueLink)malloc(sizeof(QueueNode));
	if(!qNode)
	{
		//exit(0);
		return ERROR;
	}
	qNode -> next = NULL;
	q -> front = qNode;
	q -> rear = qNode;
	q -> length = 0;
	return OK;
}

//入队列
Status InQueue(Queue *q, ElemType elem)
{
	QueueLink qNode = (QueueLink)malloc(sizeof(QueueNode));
	if(!qNode) return ERROR;
	q -> rear -> data = elem;
	q -> rear -> next = qNode;
	q -> rear = qNode;
	q -> length ++;
	return OK;
}

//出队列
Status OutQueue(Queue *q, ElemType *elem)
{
	if(q -> length == 0) return ERROR;
	QueueLink qNode;
	qNode = q -> front;
	q -> front = qNode -> next;
	*elem = qNode -> data;
	free(qNode);
	q -> length --;
	return OK;
}

//清空队列
Status Clear(Queue *q)
{
	QueueLink qNode;
	while(q -> length != 0)
	{
		qNode = q -> front;
		q -> front = qNode -> next;
		q -> length --;
		free(qNode);
	}
	return OK;
}

int main(void)
{
	Queue q;
	Status statu;
	statu = Init(&q);
	if(statu == OK)
	{
		printf("%s : %d, %d, %d\n", "Init", q.front -> data, q.rear -> data, q.length);
		statu = InQueue(&q, 21);
		if(statu == OK)
		{
			printf("%s : %d, %d, %d\n", "InQueue", q.front -> data, q.rear -> data, q.length);
			ElemType outElem;
			statu = OutQueue(&q, &outElem);
			if(statu == OK)
			{
				printf("%s : %d, %d, %d, %d\n", "OutQueue", q.front -> data, q.rear -> data, q.length, outElem);
				// InQueue(&q, 22);
				// InQueue(&q, 23);
				// printf("%s : %d, %d, %d\n", "InQueue", q.front -> data, q.rear -> data, q.length);
				statu = Clear(&q);
				if(statu == OK)
				{
					printf("%s : %d, %d, %d\n", "Init", q.front -> data, q.rear -> data, q.length);
				}
			}
		}
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值