不带头节点的链式存储队列基本操作

#include<stdio.h>
#include<malloc.h>
typedef char ElemType;
typedef struct LinkNode
{
	ElemType data;
	struct LinkNode *next;
}LinkNode;
typedef struct
{
	struct LinkNode *front,*rear;
}LinkQueue;
void InitQueue(LinkQueue &q)
{
	q.rear=q.front=NULL;		//初始化队列
}
bool IsEmpty(LinkQueue q)
{
	if(q.front==NULL)			//判空条件:头指针是否为空
		return true;
	else
		return false;
}
void EnQueue(LinkQueue &q,ElemType e)
{
	LinkNode *s=(LinkNode*)malloc(sizeof(LinkNode));
	s->data=e;
	s->next=NULL;
	if(IsEmpty(q))		//如果队列为空,则将头指针尾指针同时指向新插入的节点
	{
		q.front=s;
		q.rear=s;
		return ;
	}
	q.rear->next=s;
	q.rear=s;
}
bool DeQueue(LinkQueue &q,ElemType &e)
{
	if(q.front==NULL)
		return false;
	LinkNode *p=q.front;	//p指向头指针
	e=p->data;
	q.front=p->next;		//队列的头指针指向p指针的下一节点
	if(q.rear==p)			//此次是最后一个节点,队列置空
		q.rear=q.front=NULL;
	free(p);
	return true;
}
bool HeadQueue(LinkQueue q,ElemType &e)
{
	if(q.front==NULL)
		return e='?';
	e=q.front->data;
	return true;
}
void main()
{
	LinkQueue q;
	InitQueue(q);
	printf("The Queue is %s\n",IsEmpty(q)?"Empty":"UnEmpty");
	ElemType e;
	HeadQueue(q,e);
	printf("Head_Queue is %c\n",e);
	EnQueue(q,'a');
	EnQueue(q,'b');
	EnQueue(q,'c');
	HeadQueue(q,e);
	printf("Head_Queue is %c\n",e);
	DeQueue(q,e);
	HeadQueue(q,e);
	printf("Head_Queue is %c\n",e);
	DeQueue(q,e);
	HeadQueue(q,e);
	printf("Head_Queue is %c\n",e);
	DeQueue(q,e);
	HeadQueue(q,e);
	printf("Head_Queue is %c\n",e);
	printf("The Queue is %s\n",IsEmpty(q)?"Empty":"UnEmpty");
}

  

猜你喜欢

转载自www.cnblogs.com/-slz-2/p/13205065.html