当前位置:网站首页 > 技术博客 > 正文

顺序循环队列的实现

以下是

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; // 循环队列 的初始 长度 为5 CircularQueue 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 5 q.dequeue(); q.dequeue(); q.traverse(); // 输出 :The elements in the queue are: 3 4 5 cout << "The front element is: " << q.getFront() << endl; // 输出 :The front element is: 3 cout << "The length of the queue is: " << q.length() << endl; // 输出 :The length of the queue is: 3 return 0; }  

版权声明


相关文章:

  • maven仓库有2025-03-10 23:01:05
  • 游戏手柄测试软件2025-03-10 23:01:05
  • v4l2src2025-03-10 23:01:05
  • springboot html访问默认路径2025-03-10 23:01:05
  • iic通信协议的好处2025-03-10 23:01:05
  • 二叉树的递归遍历算法2025-03-10 23:01:05
  • hashmap数据存储结构2025-03-10 23:01:05
  • css按钮样式简约2025-03-10 23:01:05
  • 数字音频工作站的硬件系统2025-03-10 23:01:05
  • oracle rownum是什么类型2025-03-10 23:01:05