以下是
C++ 实现 循环队列的
基本操作的
代码,包括
初始化、
入队、
出队、
取队 头 元素、
遍历 输出 队列、
求 队列 长度等:
c++#include <iostream>using namespace std;const int MAXSIZE = 100; //循环队列的最大长度class CircularQueue {private:int front; // 队头指针int rear; // 队尾指针int data[MAXSIZE]; //队列数组public:CircularQueue(int n) { //初始化 队列front = rear = 0;for (int i = 0; i < n; i++) {data[i] = 0;}}bool isEmpty() { // 判断队列是否为空return front == rear;}bool isFull() { // 判断队列是否已满return (rear + 1) % MAXSIZE == front;}int length() { //求 队列 长度return (rear - front + MAXSIZE) % MAXSIZE;}bool enqueue(int x) { //入队操作if (isFull()) {return false;}data[rear] = x;rear = (rear + 1) % MAXSIZE;return true;}bool dequeue() { //出队操作if (isEmpty()) {return false; }front = (front + 1) % MAXSIZE;return true;}int getFront() { //取队 头 元素操作if (isEmpty()) {return -1;}return data[front];}void traverse() { //遍历 输出 队列if (isEmpty()) {cout << "The queue is empty." << endl;return;}cout << "The elements in the queue are: ";int i = front;while (i != rear) {cout << data[i] << " ";i = (i + 1) % MAXSIZE;}cout << endl;}};int main() {int n = 5; //循环队列的初始长度为5CircularQueue q(n);q.enqueue(1);q.enqueue(2);q.enqueue(3);q.enqueue(4);q.enqueue(5);q.traverse(); //输出:The elements in the queue are: 1 2 3 4 5q.dequeue();q.dequeue();q.traverse(); //输出:The elements in the queue are: 3 4 5cout << "The front element is: " << q.getFront() << endl; //输出:The front element is: 3cout << "The length of the queue is: " << q.length() << endl; //输出:The length of the queue is: 3return 0;}
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.mushiming.com/mjsbk/8162.html