循环队列实现
#include <iostream>
#include <Windows.h>
#include <iomanip>
#define MasSize 10
using namespace std;
typedef int DataType;
typedef struct Queue {
DataType queuq[MasSize];
int front;
int rear;
}SeqQueue;
void InitQueue(SeqQueue* SQ) {
if (!SQ) { return; }
SQ->front = 0;
SQ->rear = 0;
}
bool IsEmpty(SeqQueue* SQ) {
if (!SQ) { return false; }
if (SQ->front == SQ->rear) { cout << "队列为空" << endl; return true; }
return false;
}
bool IsFull(SeqQueue* SQ) {
if (!SQ) { return false; }
if ((SQ->rear + 1) % MasSize == SQ->front) { cout << "队列已满!" << endl; return true; }
return false;
}
bool EnterQueue(SeqQueue* SQ, DataType data) {
if (!SQ) { return false; }
if (IsFull(SQ)) { cout << "队列已满!" << endl; return false; }
SQ->queuq[SQ->rear] = data;
SQ->rear = (SQ->rear + 1) % MasSize;
return true;
}
bool Delete(SeqQueue* SQ, DataType* data) {
if (!SQ) { return false; }
if (IsEmpty(SQ)) { cout << "队列为空!" << endl; return false; }
if (!data) { return false; }
*data = SQ->queuq[SQ->front];
SQ->front = (SQ->front + 1) % MasSize;
return true;
}
int GetHead(SeqQueue* SQ, DataType* data) {
if (!SQ || IsEmpty(SQ)) { cout << "队列为空!" << endl; return false; }
return *data = SQ->queuq[SQ->front];
}
void Clear(SeqQueue* SQ) {
SQ->front = SQ->rear = 0;
}
void print(SeqQueue* SQ) {
if (!SQ) { return; }
cout << "队列中的所有数据" << endl;
for (int i = SQ->front; i != SQ->rear; i = (i + 1) % MasSize) {
cout << setw(4) << SQ->queuq[i];
}
cout << endl;
}
int getLength(SeqQueue* SQ) {
if (!SQ || IsEmpty(SQ)) { cout << "队列为空!" << endl; return false; }
int j = NULL;
j = (SQ->rear - SQ->front + MasSize) % MasSize;
return j;
}
int main(void) {
SeqQueue* SQ = new SeqQueue;
DataType data = -1;
InitQueue(SQ);
for (int i = 0; i < 9; i++) {
EnterQueue(SQ, i);
}
print(SQ);
cout << "队列中的总元素:" << getLength(SQ) << "个" << endl;
while (SQ->rear != SQ->front) {
if (Delete(SQ, &data)) {
cout << data << "出队成功!" << endl;
}
else {
cout << "出队失败!" << endl;
}
}
cout << endl;
cout << "第二次入队" << endl;
for (int i = 0; i < 9; i++) {
EnterQueue(SQ, i+10);
}
print(SQ);
cout << "队列中的总元素:" << getLength(SQ) << "个" << endl;
cout << "第二次出队" << endl;
while (SQ->rear != SQ->front) {
if (Delete(SQ, &data)) {
cout << data << "出队成功!" << endl;
}
else {
cout << "出队失败!" << endl;
}
}
delete SQ;
system("pause");
return NULL;
}