3.1顺序循环队列的表示与实习
顺序队列通常采用一维数组进行存储。其中,连续的存储单元依次存放队列中的元素。同时,使用两个指针分别表示数组中存放的第一个元素和最后一个元素的位置。指向第一个元素的叫队头指针(front),指向最后一个元素的叫队尾指针(rear)。
代码实现:(为了防止假溢出,加tag标志位)
test.c
#include <stdio.h>
#include <stdlib.h>
#define QUEUESIZE 10
typedef char DataType;
typedef struct Squeue {
DataType queue[QUEUESIZE];
int front, rear;
int tag;
}SCQueue;
//初始化
void InitQueue(SCQueue* SCQ)
{
SCQ->front = SCQ->rear = 0;
SCQ->tag = 0;
}
//队列的判空
int QueueEmpty(SCQueue SCQ)
{
if (SCQ.front == SCQ.rear && SCQ.tag==0)
{
return 1;
}
else {
return 0;
}
}
//入队
int EnQueue(SCQueue* SCQ, DataType e)
{
if (SCQ->front == SCQ->rear && SCQ->tag==1)
{
printf("队列已满!!!");
return 0;
}
SCQ->queue[SCQ->rear] = e;
SCQ->rear++;
SCQ->tag = 1;
return 1;
}
//出队
int DeQueue(SCQueue* SCQ, DataType* e)
{
if (QueueEmpty(*SCQ))
{
printf("队列已空!!!");
return 0;
}
else
{
*e = SCQ->queue[SCQ->front];
SCQ->front++;
SCQ->tag = 0;
return 1;
}
}
//输出队列
void DisplayQueue(SCQueue SCQ)
{
int i;
if (QueueEmpty(SCQ))
{
return;
}
if (SCQ.front<SCQ.rear)
{
for (i = SCQ.front; i <= SCQ.rear; i++) {
printf("%c",SCQ.queue[i]);
}
}
else
{
for (i = SCQ.front; i <= SCQ.rear+QUEUESIZE; i++) {
printf("%c", SCQ.queue[i%QUEUESIZE]);
}
}
printf("\n");
}
void main()
{
SCQueue Q;
char e = NULL;
InitQueue(&Q);
printf("A入队\n");
EnQueue(&Q, 'A');
printf("B入队\n");
EnQueue(&Q, 'B');
printf("C入队\n");
EnQueue(&Q, 'C');
printf("队列中的元素:");
DisplayQueue(Q);
printf("队头元素第一次出队:\n");
DeQueue(&Q, &e);
printf("%c\n", e);
printf("队头元素第二次出队:\n");
DeQueue(&Q, &e);
printf("%c\n", e);
printf("队头元素第三次出队:\n");
DeQueue(&Q, &e);
printf("%c\n", e);
}