实验四 循环队列的应用—加密
实验目的:
-
了解队列(操作受限的线性表)的操作特性:先进先出LIFO
-
掌握队列顺序/链式存储结构的实现(数据类型定义)
-
熟练掌握队列的基本操作:队列的初始化、出队、入队、队列是否空或满等。
实验要求:
- 熟悉教材算法3.11-3.19,采用顺序队列的方式完成本次实验任务
实验任务:
-
编程实现队列的基本操作
给定一串字符输出其加密后的内容,加密算法为:第1次将其每个字符左移1位,其中第1个字符移至倒数第1位,第2次将每个字符左移2位,其中第1个字符移至倒数第2位,第2个字符移至倒数第1位 ,依次类推。请输出给定字符经过n次加密后的内容,其中1<n<字符串长度/2,n的值运行时由用户指定。
#include<iostream>
using namespace std;
//顺序队列的基本操作
#define OK 1;
#define ERROR 0;
#define MAXQSIZE 100
#define OVERFLOW -1
typedef int QElemType;
typedef int Status;
typedef struct{
QElemType *base;
int front;
int rear;
}SqQueue;
//顺序队列的初始化
Status InitQueue(SqQueue&Q){
Q.base = new QElemType[MAXQSIZE];
if (!Q.base) exit(OVERFLOW);
Q.front = Q.rear = 0;
return OK;
}
//入队列
Status EnQueue(SqQueue &Q, QElemType e){
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){
if (Q.front == Q.rear) return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front+1) % MAXQSIZE;
return e;
}
//求队列的长度
int QueueLength(SqQueue Q){
return(Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
//读取队头元素
QElemType GetHead(SqQueue Q){
if (Q.front != Q.rear)
return Q.base[Q.front];
}
//判定队列空 / 满;
Status QEmpty_Full(SqQueue Q){
if (Q.front == Q.rear){
cout << "队列为空" << endl;
}
else if ((Q.rear + 1) % MAXQSIZE == Q.front){
cout << "队列为满" << endl;
}
else{
return OK;
}
}
//销毁顺序队列
Status DestroyQueue(SqQueue &Q){
delete(Q.base);
Q.base = NULL;
Q.front = Q.rear = 0;
cout << "队列销毁成功" << endl;
return OK;
}
//遍历顺序队列
Status QueueTraverse(SqQueue Q){
if (Q.front == Q.rear){
cout << "队列为空" << endl;
return 0;
}
while (Q.front != Q.rear){
cout << Q.base[Q.front] << " ";
Q.front++;
}
cout << endl;
return OK;
}
//加密队列
Status MoveQueue(SqQueue &Q){
QElemType head = GetHead(Q);
Q.front = (Q.front+1) % MAXQSIZE;
Q.base[Q.rear] = head; //新元素插入队尾
Q.rear = (Q.rear+1) % MAXQSIZE; //队尾指针+1
return OK;
}
int main(){
SqQueue Q;
int i=0; //队列长度
int j=0; //加密的次数
InitQueue(Q);
cout << "请输入入队个数:";
cin >> i;
cout <<"请输入入队元素 "<< endl;
for (int k = 0; k < i; k++){ //循环入队
QElemType e;
cin >> e;
EnQueue(Q, e);
}
cout << "请输入加密的次数:";
cin >> j;
for(int k=0;k<j;k++){
for(int m=0;m<=k;m++){
MoveQueue(Q);
}
}
cout << "遍历队列:";
QueueTraverse(Q);
cout << "出队元素:";
for (int j = 0; j < i; j++){
QElemType e;
cout << DeQueue(Q, e) << " ";
}
DestroyQueue(Q);
return 0;
}