您的位置:首页 > 理论基础 > 数据结构算法

数据结构(5):循环队列——队列的顺序表示和实现

2016-03-22 13:26 796 查看
/*  语言:C++                  编译环境:Visual C++6.0
循环队列——队列的顺序表示和实现
*/
#include <iostream>
#define OK 1
#define ERROR 0
#define OVERFLOW -2
// Status是函数返回值类型,其值是函数结果状态代码
typedef int Status;
// 自定义数据类型别名
typedef int QElemType;
using namespace std;

#define MAXQSIZE 100    // 队列可能达到的最大长度

// 队列的顺序存储结构
typedef struct
{
QElemType *base;    // 存储空间的基地址
int front;          // 头指针
int rear;           // 尾指针
}SqQueue;

// 循环队列都初始化
Status InitQueue(SqQueue &Q)
{
// 为队列分配一个最大容量为MAXQSIZE的数组空间
Q.base = new QElemType[MAXQSIZE];
if(!Q.base) exit(OVERFLOW);         // 存储分配失败
Q.front = Q.rear = 0;           // 头指针和尾指针置为零,队列为空
return OK;
}

// 循环队列的长度
int QueueLength(SqQueue Q)
{   // 返回Q的元素个数,即队列的长度
/* 对于非循环队列,尾指针和头指针都差值便是队列长度
对于循环队列,差值可能为负数,所以需要将差值加上
MAXQSIZE,然后与MAXQSIZE求余
*/
return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}

// 循环队列的入列
Status EnQueue(SqQueue &Q, QElemType e)
{   // 插入元素e为Q的新的队尾元素
// 尾指针在循环意义上加1后等于头指针,表明队满
if((Q.rear+1)%MAXQSIZE == Q.front)
return ERROR;
Q.base[Q.rear] = e;             // 新元素插入队尾
Q.rear = (Q.rear+1)%MAXQSIZE;   // 队尾指针+1
return OK;
}

// 循环队列的出列
Status DeQueue(SqQueue &Q, QElemType &e)
{   // 删除Q的队头元素,用e返回其值
if(Q.front == Q.rear) return ERROR; // 队空
e = Q.base[Q.front];                // 保存队头元素
Q.front = (Q.front+1)%MAXQSIZE;     // 队头指针加1

cout<<e<<" was deleted."<<endl; // 可无视...
return OK;
}

// 取循环队列都队头元素
QElemType GetHead(SqQueue Q)
{   // 返回Q的队头元素,不修改队头指针
if(Q.front != Q.rear)       // 队列非空
return Q.base[Q.front]; // 返回队头元素都值,队头指针不变
return ERROR;
}

int main()
{
SqQueue Q;
// 列表菜单
cout<<"1 InitQueue"<<endl;
cout<<"2 QueueLength"<<endl;
cout<<"3 EnQueue"<<endl;
cout<<"4 DeQueue"<<endl;
cout<<"5 GetHead"<<endl;

int choice,e;
while(1)
{
cout<<"Input a choice: ";
cin>>choice;

// 选择
switch(choice)
{
case 1:
InitQueue(Q);
continue;
case 2:
cout<<"Length: "<<QueueLength(Q)<<endl;
continue;
case 3:
EnQueue(Q,3);
continue;
case 4:
DeQueue(Q,e);
continue;
case 5:
cout<<"GetHead: "<<GetHead(Q)<<endl;
continue;
default:
cout<<"End..."<<endl;
break;
}
break;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构