20200120 数据结构和算法之 数组循环队列的实现
作者:互联网
数组循环队列针对数据量不大的情况下使用,可以快速地实现元素的入队和出队。入队和出队遵循先进先出(FIFO)的原则。结构体组成如下:
typedef int datatype;
typedef struct _loopQueue {
datatype* data;
int front;
int rear;
}loopQueue;
其中基本的操作图如下:
循环队列入队,队尾循环后移 lq->rear=(lq->rear+1)%MAX_SIZE
循环队列出队,队头循环后移lq->front=(lq->front+1)&MAX_SIZE
循环队列队空 lq->front=lq->rear=0;//初始化时指向同一位置
循环队列满 (lq->rear+1)%MAX_SIZE=lq->front
队列的长度计算,分两种情况: 如果 lq->rear> lq->front
队列长度为 lq->rear-lq->front;若lq->rearfront,队列长度为 MAX_SZIE-lq->front-lq->rear),即 lq->rear-lq->front+MAX_SIZE;
统一上述两种情况 长度为(lq->rear-lq->front+MAX_SIZE)%MAX_SIZE
完整的代码实现如下:
#include<Windows.h>
#include<iostream>
using namespace std;
#define MAX_SZIE 5
typedef int datatype;
typedef struct _loopQueue {
datatype* data;
int front;
int rear;
}loopQueue;
bool initLoopQueue(loopQueue* &lq);
bool isFull(loopQueue* &lq);
int getLength(loopQueue* &lq);
void loopQueuePrint(loopQueue*& lq);
bool loopQueueEnter(loopQueue*& lq, datatype data);
bool loopQueueDelete(loopQueue*& lq, datatype &data);
int main() {
loopQueue* lq;
if(!initLoopQueue(lq)) {
cout << "初始化失败!" << endl;
exit(1);
}
for (int i = 0; i < 10; i++) {
if (loopQueueEnter(lq, i)) {
cout << "入队成功:"<<i<<endl;
}
else {
cout << "入队失败:" << i << endl;
}
}
cout << "队列的长度为:" << getLength(lq)<<endl;
int data;
for (int i = 0; i < 2; i++) {
if (loopQueueDelete(lq, data)) {
cout << "出队成功:" << data << endl;
}
else {
cout << "出队失败:" << endl;
}
}
for (int i = 10; i < 15; i++) {
if (loopQueueEnter(lq, i)) {
cout << "入队成功:" << i << endl;
}
else {
cout << "入队失败:" << i << endl;
}
}
cout << "队列的长度为:" << getLength(lq) << endl;
loopQueuePrint(lq);
system("pause");
return 0;
}
bool initLoopQueue(loopQueue* &lq) {
lq = new loopQueue;
if (!lq) return false;
lq->data = new datatype[MAX_SZIE];
memset(lq->data, 0, MAX_SZIE);
lq->front = lq->rear = 0;
return true;
}
bool isFull(loopQueue*& lq) {
if (!lq) return false;
if ((lq->rear + 1) % MAX_SZIE == lq->front)
return true;
else
return false;
}
int getLength(loopQueue*& lq) {
if (!lq) return false;
return (lq->rear - lq->front + MAX_SZIE) % MAX_SZIE;
}
void loopQueuePrint(loopQueue* &lq) {
if (!lq || lq->front == lq->rear) return;
int tmp = lq->front;
while (1) {
datatype num = lq->data[tmp];
cout << num << " ";
tmp=(tmp+1)% MAX_SZIE;
if (tmp == lq->rear) break;
}
}
bool loopQueueEnter(loopQueue*& lq, datatype data) {
if (!lq || isFull(lq)) return false;
lq->data[lq->rear] = data;
lq -> rear = (lq->rear + 1) % MAX_SZIE;
return true;
}
bool loopQueueDelete(loopQueue*& lq, datatype& data) {
if (!lq || lq->front == lq->rear) return false;
data = lq->data[lq->front];
lq->front = (lq->front + 1) % MAX_SZIE;
return true;
}
lee李家军
发布了53 篇原创文章 · 获赞 0 · 访问量 2096
私信
关注
标签:数据结构,队列,MAX,loopQueue,lq,front,20200120,data,rear 来源: https://blog.csdn.net/weixin_40071289/article/details/104050208