当队列不为空的时候,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();
}