链队列的C语言实现

本文详细介绍了如何使用C语言实现队列的基本操作,并通过实例展示了队列在实际编程中的应用。

下面的代码实现了除销毁队列以外的所有队列操作:

#include 
#include 

#ifndef TRUE
#define TRUE	1
#endif
#ifndef FALSE
#define FALSE	(!TRUE)
#endif

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

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

LinkQueue  InitQueue(LinkQueue *Q)
{
	QueuePtr  tmp;
	tmp = (QueuePtr)malloc(sizeof(QNode));
	if(tmp == NULL){
		printf("create queue error.\n");
		return ;
	}
	Q->front = tmp;
	Q->rear = Q->front;
	Q->front->next = NULL;

	return *Q;
}

void EnQueue(LinkQueue *Q, QElemType e)
{
	QueuePtr	tmp;
	tmp = (QueuePtr)malloc(sizeof(QNode));
	if(tmp == NULL){
		printf("create queue error.\n");	
		return ;
	}
	tmp->data = e;
	tmp->next = NULL;
	Q->rear->next = tmp;
	Q->rear = tmp;

	return;
}

void DeQueue(LinkQueue *Q, QElemType *e)
{
	QueuePtr tmp;
	if(Q->front == Q->rear){
		printf("the queue is empty.\n");	
		return ;
	}
	tmp = Q->front->next;
	*e = tmp->data;
	Q->front->next = tmp->next;
	if(Q->rear == tmp)
		Q->rear = Q->front;
	free(tmp);
	return;
}

int QueueLength(LinkQueue Q)
{
	int length = 0;
	while(Q.front != Q.rear){
		length++;
		Q.front = Q.front->next;	
	}

	return length - 1;
}

void GetHead(LinkQueue *Q, QElemType *e)
{
	if(Q->front == Q->rear)
		return;
	*e = Q->front->next->data;
	return ;
}

int QueueEmpty(LinkQueue *Q)
{
	if(Q->front == Q->rear)
		return TRUE;
	return FALSE;
}

void ClearQueue(LinkQueue *Q)
{
	if(Q->front == Q->rear){
		printf("the queue is empty.\n");
		return;
	}

	while(Q->front->next){
		Q->rear = Q->front->next->next;
		free(Q->front->next);	
		Q->front = Q->front->next;
	}
	Q->front->next = NULL;
	Q->rear = Q->front;
	return;
}

#if 0
void DestroyQueue(LinkQueue *Q)
{
	ClearQueue(Q);
	return;
}
#endif

int 
main(void)
{
	QElemType *e;
	int length;
	Q = InitQueue(&Q);

	EnQueue(&Q, 3);
	EnQueue(&Q, 5);
	EnQueue(&Q, 2);

	DeQueue(&Q, e);
	printf("e = %d\n", *e);

	GetHead(&Q, e);
	printf("e = %d\n", *e);

	length = QueueLength(Q);
	printf("length = %d\n", length);

	ClearQueue(&Q);

	if(QueueEmpty(&Q))
		printf("the queue is empty.\n");
	else
		printf("the queue is not empty.\n");

	//DestroyQueue(&Q);

	return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值