说明:这里循环队列的实现方式是 少用一个元素空间
注意:队列时尾插头删
1.入队分析:
void EnQueue(SqQueue *Q, QElemType e)
{
if ((Q->rear+1) % MAXQSIZE == Q->front)
{
printf("队列已满,无法插入\n");
exit(-1);
}
printf("入队元素为:%d\n", e);
Q->base[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAXQSIZE;
}
2.出队分析:
void DeQueue(SqQueue *Q)
{
if (Q->rear == Q->front)
{
printf("队列已空\n");
exit(-1);
}
printf("出队元素为:%d\n", Q->base[Q->front]);
Q->front = (Q->front +1) % MAXQSIZE;
}
3.代码实现:
#include<stdio.h>
#include<stdlib.h>
#define MAXQSIZE 100
typedef int QElemType;
typedef struct
{
QElemType *base;
int front;
int rear;
}SqQueue;
void InitQueue(SqQueue *Q)
{
Q->base = (QElemType*)malloc(MAXQSIZE * sizeof(QElemType));
if (!Q->base)
exit(-1);
Q->front = 0;
Q->rear = 0;
}
int QueueLength(SqQueue *Q)
{
return((Q->rear - Q->front + MAXQSIZE) % MAXQSIZE);
}
void EnQueue(SqQueue *Q, QElemType e)
{
if ((Q->rear+1) % MAXQSIZE == Q->front)
{
printf("队列已满,无法插入\n");
exit(-1);
}
printf("入队元素为:%d\n", e);
Q->base[Q->rear] = e;
Q->rear = (Q->rear + 1) % MAXQSIZE;
}
void DeQueue(SqQueue *Q)
{
if (Q->rear == Q->front)
{
printf("队列已空\n");
exit(-1);
}
printf("出队元素为:%d\n", Q->base[Q->front]);
Q->front = (Q->front +1) % MAXQSIZE;
}
QElemType GetHead(SqQueue *Q)
{
if (Q->front != Q->rear)
return Q->base[Q->front];
else
exit(-1);
}
void test1()
{
SqQueue Q;
InitQueue(&Q);
EnQueue(&Q, 1);
EnQueue(&Q, 2);
EnQueue(&Q, 3);
EnQueue(&Q, 4);
int length=QueueLength(&Q);
printf("队列长度尾%d\n\n", length);
DeQueue(&Q);
DeQueue(&Q);
DeQueue(&Q);
length = QueueLength(&Q);
printf("队列长度尾%d\n\n", length);
int head = GetHead(&Q);
printf("队头元素为:%d\n", head);
}
int main()
{
test1();
return 0;
}
|