1.队列的定义:
队列( queue ) 是只允许在一端进行插入操作,而在另-端进行删除操作的线性表。
队列是一种先进先出( First 10 First Out) 的线性表,简称FIFO 。允许插入的一
端称为队尾,允许删除的一端称为队头。
循环队列:
2.代码的实现:
队列的抽象:
//定义队列抽象数据
typedef int QElemType;
#define MAXSIZE 10
typedef struct
{
QElemType data[MAXSIZE];
int front; //头指针
int rear; //尾指针
}SqQueue;
//队列初始化
void InitQuene(SqQueue &Q)
{
Q.front = 0;
Q.rear = 0;
printf("初始化队列\n");
}
//求队列长队
int QueueLength(SqQueue &Q)
{
return (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
}
//队列未满,则插入元素e为Q新的队尾元素
void InQueue(SqQueue &Q, QElemType e)
{
if ((Q.rear + 1) % MAXSIZE == Q.front)
cout << "队列满了" << endl;
Q.data[Q.rear] = e;
Q.rear = (Q.rear+1)%MAXSIZE; //rear指针后移一位
cout << "入队" << e << endl;
}
/*出队列*/
void OutQueue(SqQueue &Q, QElemType &e)
{
/*判断队列是否为空*/
if (Q.front == Q.rear)
cout << "队列空" << endl;
e = Q.data[Q.front];
Q.front = (Q.front + 1) % MAXSIZE;
cout << "出队" << e << endl;
}
/*打印队列中的元素*/
void PrintQueue(SqQueue Q)
{
for (int i = Q.front; i%MAXSIZE<Q.rear; i++)
{
printf("%d\n", Q.data[i]);
}
}
void main()
{
SqQueue Q;
InitQuene(Q);
printf("入队列测试:\n");
/*入队列测试*/
InQueue(Q, 1);
InQueue(Q, 2);
InQueue(Q, 3);
InQueue(Q, 4);
InQueue(Q, 5);
InQueue(Q, 6);
InQueue(Q, 7);
InQueue(Q, 8);
InQueue(Q, 9);
PrintQueue(Q);
printf("溢出测试:\n");
/*溢出测试*/
InQueue(Q, 10);
PrintQueue(Q);
printf("出队列测试:\n");
/*出队列测试*/
QElemType e;
OutQueue(Q, e);
printf("%d\n", e);
OutQueue(Q, e);
printf("%d\n", e);
printf("长度测试:\n");
/*长度测试*/
printf("%d\n", QueueLength(Q));
system("pause");
}