/** * File: array_queue.cpp * Created Time: 2022-11-25 * Author: krahets (krahets@163.com) */ #include "../utils/common.hpp" /* 基于环形数组实现的队列 */ class ArrayQueue { private: int *nums; // 用于存储队列元素的数组 int front; // 队首指针,指向队首元素 int queSize; // 队列长度 int queCapacity; // 队列容量 public: ArrayQueue(int capacity) { // 初始化数组 nums = new int[capacity]; queCapacity = capacity; front = queSize = 0; // 初始化队首指针和队列长度 } ~ArrayQueue() { delete[] nums; // 释放内存 } /* 获取队列的容量 */ int capacity() { return queCapacity; } /* 获取队列的长度 */ int size() { return queSize; } /* 判断队列是否为空 */ bool isEmpty() { return size() == 0; } /* 入队 */ void push(int num) { if (queSize == queCapacity) { cout << "队列已满" << endl; // 队列已满,无法入队 return; } // 计算队尾指针,指向队尾索引 + 1 // 通过取余操作实现 rear 越过数组尾部后回到头部 int rear = (front + queSize) % queCapacity; // 将 num 添加至队尾 nums[rear] = num; queSize++; } /* 出队 */ int pop() { int num = peek(); // 队首指针向后移动一位,若越过尾部,则返回到数组头部 front = (front + 1) % queCapacity; queSize--; return num; } /* 访问队首元素 */ int peek() // peek 意为窥视,这里指查看队首元素 { if (isEmpty()) throw out_of_range("队列为空"); return nums[front]; } /* 将数组转化为 Vector 并返回 */ vector toVector() { // 仅转换有效长度范围内的列表元素 vector arr(queSize); for (int i = 0, j = front; i < queSize; i++, j++) { arr[i] = nums[j % queCapacity]; } return arr; } }; /* Driver Code */ int main() { /* 初始化队列 */ int capacity = 10; // 队列容量 ArrayQueue *queue = new ArrayQueue(capacity); /* 元素入队 */ queue->push(1); queue->push(3); queue->push(2); queue->push(5); queue->push(4); cout << "队列 queue = "; printVector(queue->toVector()); /* 访问队首元素 */ int peek = queue->peek(); cout << "队首元素 peek = " << peek << endl; /* 元素出队 */ peek = queue->pop(); cout << "出队元素 pop = " << peek << ",出队后 queue = "; printVector(queue->toVector()); /* 获取队列的长度 */ int size = queue->size(); cout << "队列长度 size = " << size << endl; /* 判断队列是否为空 */ bool empty = queue->isEmpty(); cout << "队列是否为空 = " << empty << endl; /* 测试环形数组 */ for (int i = 0; i < 10; i++) { queue->push(i); queue->pop(); cout << "第 " << i << " 轮入队 + 出队后 queue = "; printVector(queue->toVector()); } // 释放内存 delete queue; return 0; }