#include<stdio.h>
#include<stdlib.h>
#define MAXQSIZE 100
int tag = 0;
int sum = 0;
typedef struct
{
int *base;//存储空间的基地址
int front;//头指针
int rear;//尾指针
}SqQueue;
//判断队满队空的3种方法队满为true,队空为false
//方法一:设标志位法
bool Judge1(SqQueue &Q)
{
if (tag == 0 && Q.front == Q.rear)
return false;
if (tag == 1 && Q.front == Q.rear)
return true;
}
//方法二:预留一位法
bool Judge2(SqQueue &Q)
{
if ((Q.rear + 1) % MAXQSIZE == Q.front)
return true;
if (Q.rear == Q.front)
return false;
}
//方法三:预存长度法
bool Judge3(SqQueue &Q)
{
if (sum == MAXQSIZE)
return true;
if (sum == 0)
return false;
}
//循环队列的初始化
void InitQueue(SqQueue &Q)
{
Q.base = new int[MAXQSIZE];
if (!Q.base) exit(0);
Q.front = Q.rear = 0;
}
//求循环队列的长度
int QueueLength(SqQueue Q)
{
return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;//加上MAXSIZE是为了当队满时头指针和尾指针相等时的这一情况
}
//循环队列入队(采用预留一位法来判断队空队满)
void EnQueue(SqQueue &Q, int e)
{
if (Judge2(Q) == true)
{
printf(“队列已满!”);
return;
}
Q.base[Q.rear] = e;
Q.rear = ((Q.rear + 1) % MAXQSIZE);
}
//循环队列出队(采用预留一位法来判断队空队满)
void DeQueue(SqQueue &Q, int &e)
{
if (Judge2(Q) == false)
{
printf(“队列是空的!”);
return;
}
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
}
//取队头元素(采用预留一位法来判断队空队满)
int GetHead(SqQueue Q)
{
if (Judge2(Q) != false)
return Q.base[Q.front];
}
int main()
{
SqQueue a;
int b,d;
InitQueue(a);
EnQueue(a, 1);
EnQueue(a, 2);
b = GetHead(a);
d = QueueLength(a);
printf(“队头元素为%d,队列长度为%d\n”, b,d);
system(“pause”);
return 0;
}