队列——链表实现

引言:

   

       队列与栈的区别是队列是先进先出的数据结构。为了使得出入队列容易,可以引入队列头指针和队列尾指针。


分析描述:


       队列的结点结构。

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;
}

        取队列的头元素。

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;
}

          求队列的长度。

int QueueLength(LinkQueue Q)
{
	int length = 0;
	LinkQueue Tmp= Q;

	while(Tmp.front != Tmp.rear){
		length++;
		Tmp.front = Tmp.front->next;	
	}

	return length - 1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值