顺序队列

当队列不为空的时候,front永远正对着第一个元素,rear永远在最后一个元素的后面


void Traverse(int a[],int length,int pos)
{
int flag = pos;
while (pos  != flag -1)
{
printf("%d\n",a[pos]);
pos = (++pos)%length; //求余是关键
}
printf("%d",a[pos]);
}从pos位置
遍历数组,可以循环遍历


队列为满,队列为空的各自条件不一样,满的时候那个数组一定会空一格元素出来

#include "stdio.h"    
#include "stdlib.h"   
#include "io.h"  
#include "math.h"  
#include "time.h"

#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 20 /* 存储空间初始分配量 */

typedef int Status; 
typedef int QElemType; /* QElemType类型根据实际情况而定,这里假设为int */

typedef struct 
{
	QElemType data[MAXSIZE];
	int front;
	int rear;
}SqQueue;

Status visit(QElemType e)
{
	printf("%d\n",e);
	return OK;
}
//对于顺序结构的队列,其实也就是数组类型的队列如何初始化,初始化的时候由于是数组,所以不需要申请空间
//只需要将头尾指针指在0位即可

Status InitQueue(SqQueue *q)
{
	q->front = 0;
	q->rear = 0;
	return OK;
}
//清除队列和初始化队列是一样的
Status  ClearQueue(SqQueue *q) 
{
	q->front = 0;
	q->rear = 0;
	return OK;
}
//对于数组类型的队列,初始化,清除,空队列
Status QueueEmpty(SqQueue q)
{
	if (q.front ==q.rear)
	{
		return OK;
	}
	return FALSE;
}

int QueueLength(SqQueue q)
{
	return  (q.rear - q.front + MAXSIZE)%MAXSIZE;
}

Status GetHead(SqQueue Q,QElemType *e)
{
	/*如果队列不为空,则才可以去第一个元素*/
	if (Q.front == Q.rear)
	{
		return ERROR;
	}
	*e = Q.data[Q.front];
}
Status EnQueue(SqQueue *Q,QElemType e)
{
	/*如果队列满则无法加入队列*/
	if ((Q->rear + 1)%MAXSIZE == Q->front)
	{
		return ERROR;
	}
	Q->data[Q->rear] = e;
	Q->rear = (Q->rear ++)%MAXSIZE;
	return OK;
}

/*若队列为空时,则返回假*/
Status DeQueue(SqQueue *Q,QElemType *e)
{
	if (Q->front == Q->rear)
	{
		return FALSE;
	}
	*e = Q->data[Q->front];
	Q->front = (Q->front+1)%MAXSIZE;
	return OK;
}

Status QueueTraverse(SqQueue Q)
{
	int i = Q.front;
	while ((Q.front + i) != Q.rear )
	{
		visit(Q.data[i]);
		i++;
		i = i%MAXSIZE;
	}
	printf("\n");
	return OK;
}

void Traverse(int a[],int length,int pos)
{
	int flag = pos;
	while (pos  != flag -1)
	{
		printf("%d\n",a[pos]);
		pos = (++pos)%length;
	}
	printf("%d",a[pos]);
}

void main()
{	
	SqQueue Q;
	int d,i;
	d = 0;
	i = 0;
	InitQueue(&Q);
	printf("初始化队列后,队列空否?%u(1:空 0:否)\n",QueueEmpty(Q));
	do
	{
		/* scanf("%d",&d); */
		d=i+100;
		i++;
		EnQueue(&Q,d);
	}while(i<MAXSIZE -1);

	printf("队列长度为: %d\n",QueueLength(Q));
	printf("现在队列空否?%u(1:空 0:否)\n",QueueEmpty(Q));
	QueueTraverse(Q);
	for ( i=0; i<19; i++)
	{
		DeQueue(&Q,&d);
		printf("开始出队列");
		printf("%d\n",d);
		printf("队列长度为: %d\n",QueueLength(Q));
	}
	getchar();
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值