// 循环队列的实现 #include #include using namespace std; #define MAXQSIZE 100 #define OK 1 #define ERROR 0 #define OVERFLOW -1 typedef char QElemType; typedef char SElemType; typedef int Status; // 定义队列结构体 struct SqQueue { QElemType* base; // 分配内存空间 int front; // 头指针 int rear; // 尾指针 }; // 初始化循环队列 Status InitQueue(SqQueue &Q) { Q.base = new QElemType[MAXQSIZE]; // 分配内存空间 if (!Q.base) { exit(OVERFLOW); } Q.front = Q.rear = 0; return OK; } // 获取循环队列的长度 int GetQueueLength(SqQueue Q) { return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE; } // 循环队列入队 Status EntryQueue(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 OutputQueue(SqQueue& Q, QElemType& e) { if (Q.rear == Q.front) { return ERROR; // 循环队列为空 } e = Q.base[Q.front]; Q.front = (Q.front + 1) % MAXQSIZE; // 头指针+1 return OK; } // 获取循环队列的第一个元素 SElemType GetHeadQueue(SqQueue Q) { if (Q.front != Q.rear) { return Q.base[Q.front]; // 返回循环队列的第一个元素 } } int main() { int choose, flag = 0; SqQueue Q; QElemType e, j; cout << " 1.队列初始化"<< endl; cout << " 2.入队" << endl; cout << " 3.出队" << endl; cout << " 4.获取第一个元素" << endl; cout << " 0.退出" << endl; choose = -1; while (choose != 0) { cout << "请选择循环队列的操作项【0-4】:"; cin >> choose; switch (choose) { case 1: if (InitQueue(Q)) { flag = 1; cout << "循环队列初始化成功" << endl; } else { cout << "循环队列初始化失败" << endl; } break; case 2: { fstream file; file.open("Queue.txt"); if (!file) { cout << "文件打开失败" << endl; return ERROR; } if (flag) { flag = 1; cout << "循环队列入队元素依次为:" << endl; while (!file.eof()) { file >> j; if (file.fail()) { break; } else { EntryQueue(Q, j); cout << j << " "; } } cout << endl; } else { cout << "循环队列未创建" << endl; } file.close(); } break; case 3: cout << "循环队列依次出队的元素为:" << endl; while (OutputQueue(Q,e)) { flag = -1; cout << e << " "; } cout << endl; break; case 4: if (flag != -1 && flag != 0) { cout << "循环队列的第一个元素为:" << GetHeadQueue(Q) << endl; } else { cout << "队列中无元素" << endl; } break; } } return 0; }