链队列

   队列(Queue)也是一种运算受限的线性表。它只允许在表的一端进行插入,而在另一端进行删除。允许删除的一端称为队头(front),允许插入的一端称为队尾(rear)


1队列初始化
#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>

#define OK 1
#define  ERROR 1
#define  TRUE 1
#define  FALSE 1
#define  OVERFLOW -1

typedef int Status;
typedef int QElemType;

typedef struct QNode{/*定义结点*/
	QElemType data;
	struct QNode *next;
}QNode,*PtrQueue;

typedef struct{

	PtrQueue front;/*队头队尾指针*/
	PtrQueue rear;
}LinkQueue;

/*队列初始化*/
Status InitQueue(LinkQueue *Q)
{
	Q->front=Q->rear=(PtrQueue)malloc(sizeof(QNode));//申请内存空间
	if(!Q->front)
		exit(OVERFLOW);
	else
		Q->front->next=NULL;/*构造一个空队列*/
	return OK;
}


2销毁队列

/*销毁队列*/
Status DestroyQueue(LinkQueue *Q)
{
	while(Q->front)
	{
		Q->rear=Q->front->next;
		free(Q->front);
		Q->front=Q->rear;
	}
	return OK;
}
3将队列清空

/*将队列清空*/
Status ClearQueue(LinkQueue *Q)
{
	PtrQueue p,q;
	Q->rear=Q->front;
	p=Q->front->next;
	while(p)
	{
		q=p;
		p=p->next;
		free(q);
	}
	return OK;
}

4判断队列是否为空

/*判断队列是否为空*/
Status EmptyQueue(LinkQueue Q)
{
	if (Q.front==Q.rear)
	{
		return TRUE;
	}
	else
		return FALSE;
}

5求队列的长度

/*求队列的长度*/
int QueueLength(LinkQueue Q)
{
	int i=0;
	PtrQueue p;
	p=Q.front;
	while(p!=Q.rear)
	{
		i++;
		p=p->next;
	}
	return i;
}

6入队

/*入队*/
Status EnQueue(LinkQueue *Q,QElemType e)
{
	PtrQueue s=(PtrQueue)malloc(sizeof(QNode));//新结点
	if (!s)
		exit(OVERFLOW);
	s->data=e;
	s->next=NULL;
	Q->rear->next=s;
	Q->rear=s;
	return OK;
}

7出队

/*出队*/
 Status DeQueue(LinkQueue *Q, QElemType *e)
 {
 	PtrQueue p;
 	if (Q->front==Q->rear)
 	exit(OVERFLOW);
 	p=Q->front->next;//欲删除的队头结点
 	*e=p->data;
 	Q->front->next=p->next;
 	if (p==Q->rear)//若队头就是队尾,删除后队尾指向头结点
 	{
 		Q->rear=Q->front;
 	}
 	free(p);
 	return OK;
 }

8遍历队列

/*遍历队列*/
Status TraverseQueue(LinkQueue Q)
{
	PtrQueue p;
	p=Q.front->next;
	while(p)
	{
		printf("%d ",p->data);
		p=p->next;
	}
	printf("\n");
	return OK;
}

9主程序

int main()
{
	int i;
	int L;
	QElemType e;//保存出队数据
	LinkQueue Q;//定义一个队列
	InitQueue(&Q);
	printf("初始化后的长度为%d \n",QueueLength(Q));
	for (i=1; i<10; i++)
	{
		EnQueue(&Q,i);
	}
	printf("入队1~9\n");
	TraverseQueue(Q);
	printf("队列长度:%d\n",L=QueueLength(Q));
	printf("依次出队\n");
	while (L)
	{
		DeQueue(&Q,&e);
		printf("%d ",e);
		L--;
	}
	printf("\n");
}

10程序运行结果


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值