//循环队列顺序表示,队列初始化,求队列长度,入队,出队,打印队列中的元素,求队头元素
include <stdio.h>
include <stdlib.h>
define MAXQSIZE 10
typedef struct
{
int data[MAXQSIZE];
int front; //头指针
int rear; //尾指针
} SqQueue;
void *InitQueue(SqQueue Q)
{
SqQueue *q;
q = (SqQueue *)malloc(sizeof(SqQueue));
q->front = q->rear = 0; //头指针和尾指针置为零,队列为空
return q;
}
int QueueLength(SqQueue *Q)
{
int len;
len = (Q->rear - Q->front + MAXQSIZE) % MAXQSIZE; //求元素个数,即队列长度
printf("长度为:%d\n", len);
return 0;
}
int EnQueue(SqQueue *q, int e)
{
if ((q->rear + 1) % MAXQSIZE == q->front) //尾指针在循环意义上加1后等于头指针,表明队满
{
printf("队满");
}
printf("输入:");
scanf("%d", &e);
q->data[q->rear] = e; //新元素插入队尾
q->rear = (q->rear + 1) % MAXQSIZE; //队尾指针加1
return 0;
}
int DeQueue(SqQueue *q, int *e) //删除队头元素,用e返回其值
{
if (q->front == q->rear) //队空
{
printf("error");
}
*e = q->data[q->front]; //保存队头元素
q->front = (q->front + 1) % MAXQSIZE; //队头指针加1
return 0;
}
void showQueue(SqQueue *Q)
{
int i = Q->front;
printf("队列中的元素是:");
while (i != Q->rear)
{
printf("%d ", Q->data[i]);
i++;
i = i % MAXQSIZE;
}
printf("\n");
}
int GetHead(SqQueue *q)
{
int e;
if (q->front != q->rear) //队列非空
{
e = q->data[q->front];
}
printf("%d\n", e);
return 0;
}
int main()
{
int e;
SqQueue q;
q = InitQueue(q);
printf("将元素1插入到队尾后的结果:\n");
EnQueue(q, e);
QueueLength(q);
showQueue(q);
printf("将元素2插入到队尾后的结果:\n");
EnQueue(q, e);
QueueLength(q);
showQueue(q);
printf("将元素3插入到队尾后的结果:\n");
EnQueue(q, e);
QueueLength(q);
showQueue(q);
DeQueue(q, &e);
printf("出队的元素是:%d\n", e);
QueueLength(q);
showQueue(q);
printf("队头元素为:");
GetHead(q);
return 0;
}