(8)数据结构-循环队列
原创
©著作权归作者所有:来自51CTO博客作者mb5dbc2345bf8de的原创作品,请联系作者获取转载授权,否则将追究法律责任
文章目录
- 前言
- 1、简介
- 2、数据结构
- 3、基本操作
- 3.1初始化
- 3.2 判断队空
- 3.3 入队
- 3.4 出队
- 3.5 获取长度
前言
代码这种东西,每个人的想法或多或少有点不一样,不用死磕某一个人的代码,而是要靠自己思考出来数据之间的变化,写出属于自己的代码。
1、简介
1.1 定义
循环队列是基于队列改进的数据结构。
初始化:rear = front =0
队空:rear == front
队满:rear+1 == front。
2、数据结构
循环队列的数据结构有多种,但是万变不离其宗,不过是换一种方式表达信息罢了。
typedef struct{
ElemType Data[MaxSize];
int front,rear;
}SqQueue;
3、基本操作
3.1初始化
SqQueue InitQueue(SqQueue Q){
Q.front = Q.rear = 0;
return Q;
}
3.2 判断队空
bool Empty(SqQueue Q){
if (Q.front == Q.rear){
return true;
}else{
return false;
}
}
3.3 入队
bool EnQueue(SqQueue &Q, int x){
if ((Q.rear+1)%MaxSize == Q.front){
cout << "Queue is Full" << endl;
return false;
}else{
Q.Data[Q.rear] = x;
cout << "EnQueue Successfully:" << Q.Data[Q.rear] << endl;
Q.rear = (Q.rear+1)%MaxSize;
return true;
}
}
3.4 出队
bool DeQueue(SqQueue &Q, int &x){
if (Empty(Q)){
cout << "Queue Empty" << endl;
return false;
}else{
x = Q.Data[Q.front];
Q.front = (Q.front+1)%MaxSize;
cout << "DeQueue Successfully:" << x << endl;
return true;
}
}
3.5 获取长度
int GetLen(SqQueue Q){
return (Q.rear-Q.front+MaxSize) % MaxSize;
}
4、完整代码
#include<iostream>
using namespace std;
typedef int ElemType;
#define MaxSize 50
#define Error -1
typedef struct{
ElemType Data[MaxSize];
int front,rear;
}SqQueue;
SqQueue InitQueue(SqQueue Q);
bool Empty(SqQueue Q);
bool EnQueue(SqQueue &Q, int x);
bool DeQueue(SqQueue &Q, int &x);
int GetLen(SqQueue Q);
int main(){
SqQueue Q = InitQueue(Q);
cout << Q.rear << " " << Q.front << endl;
EnQueue(Q,12);
EnQueue(Q,45);
cout << "Len of Queue is:" << GetLen(Q) << endl;
int x;
DeQueue(Q,x);
DeQueue(Q,x);
cout << "Len of Queue is:" << GetLen(Q) << endl;
return 0;
}
SqQueue InitQueue(SqQueue Q){
Q.front = Q.rear = 0;
return Q;
}
bool Empty(SqQueue Q){
if (Q.front == Q.rear){
return true;
}else{
return false;
}
}
bool EnQueue(SqQueue &Q, int x){
if ((Q.rear+1)%MaxSize == Q.front){
cout << "Queue is Full" << endl;
return false;
}else{
Q.Data[Q.rear] = x;
cout << "EnQueue Successfully:" << Q.Data[Q.rear] << endl;
Q.rear = (Q.rear+1)%MaxSize;
return true;
}
}
bool DeQueue(SqQueue &Q, int &x){
if (Empty(Q)){
cout << "Queue Empty" << endl;
return false;
}else{
x = Q.Data[Q.front];
Q.front = (Q.front+1)%MaxSize;
cout << "DeQueue Successfully:" << x << endl;
return true;
}
}
int GetLen(SqQueue Q){
return (Q.rear-Q.front+MaxSize) % MaxSize;
}