liqueue.h 代碼
/*
*Copyright (c) 2017, 煙臺大學計算機與控制工程學院
*All rights reserved.
*文件名稱:
*作 者:陳軍正
*完成日期:2017年10月22日
*版 本 號:v1.0
*
*/
#define MaxSize 5
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int front, rear; /*隊首和隊尾指針*/
} SqQueue;
void InitQueue(SqQueue *&q); //初始化順序環形隊列
void DestroyQueue(SqQueue *&q); //銷燬順序環形隊列
bool QueueEmpty(SqQueue *q); //判斷順序環形隊列是否爲空
int QueueLength(SqQueue *q); //返回隊列中元素個數,也稱隊列長度
bool enQueue(SqQueue *&q, ElemType e); //進隊
bool deQueue(SqQueue *&q, ElemType &e); //出隊
main.cpp 代碼
#include <malloc.h>
#include "liqueue.h"
#include <iostream>
using namespace std;
int main()
{
ElemType a, x;
SqQueue *qu; //定義隊列
InitQueue(qu); //隊列初始化
while (1)
{
cout<<"輸入a值(輸入正數進隊,負數出隊,0結束):";
cin >> a;
if (a>0)
{
if (!enQueue(qu, a))
cout << " 隊列滿,不能入隊" << endl;;
}
else if (a<0)
{
if (!deQueue(qu, x))
cout<<" 隊列空,不能出隊";
}
else if (a==0)
{
break;
}
}
return 0;
}
liqueue.cpp 代碼
#include <malloc.h>
#include "liqueue.h"
void InitQueue(SqQueue *&q) //初始化順序環形隊列
{
q = (SqQueue *)malloc(sizeof(SqQueue));
q->front = q->rear = 0;
}
void DestroyQueue(SqQueue *&q) //銷燬順序環形隊列
{
free(q);
}
bool QueueEmpty(SqQueue *q) //判斷順序環形隊列是否爲空
{
return(q->front == q->rear);
}
int QueueLength(SqQueue *q) //返回隊列中元素個數,也稱隊列長度
{
return (q->rear - q->front + MaxSize) % MaxSize;
}
bool enQueue(SqQueue *&q, ElemType e) //進隊
{
if ((q->rear + 1) % MaxSize == q->front) //隊滿上溢出
return false;
q->rear = (q->rear + 1) % MaxSize;
q->data[q->rear] = e;
return true;
}
bool deQueue(SqQueue *&q, ElemType &e) //出隊
{
if (q->front == q->rear) //隊空下溢出
return false;
q->front = (q->front + 1) % MaxSize;
e = q->data[q->front];
return true;
}
運行結果總結:熟悉環形隊列基本運算的運用