循環隊列的初始化、入隊、出隊等基本操作,實現代碼如下:
#include<iostream>
using namespace std;
#define TRUE 1
#define FALSE 0
//循環隊列的類型定義
#define MAXSIZE 50//隊列的最大長度
typedef struct
{
int element[MAXSIZE];//隊列的元素空間
int front;//頭指針指示器
int rear;//尾指針指示器
}SeqQueue;
//循環隊列初始化
void InitQueue(SeqQueue *Q)//將*Q初始化爲一個空的循環隊列
{
Q->front = Q->rear = 0;
}
//循環隊列入隊
int EnterQueue(SeqQueue *Q, int x)//將元素x入隊
{
if ((Q->rear + 1) % MAXSIZE == Q->front)//尾指針加1追上頭指針,標誌隊列已經滿了
{
return FALSE;
}
Q->element[Q->rear] = x;
Q->rear = (Q->rear + 1) % MAXSIZE;//重新設置隊尾指針
return TRUE;
}
//循環隊列出隊
int DeleteQueue(SeqQueue *Q, int *x)//刪除隊列的隊頭元素,用x返回其值
{
if (Q->rear == Q->front)//隊列爲空
{
return FALSE;
}
*x=Q->element[Q->front] ;
Q->front = (Q->front + 1) % MAXSIZE;//重新設置隊頭指針
return TRUE;
}