这是使用数组实现的循环队列,同样也可以用链表实现,但原理都是一样的,就不重新写一份了,简单实现了数据的取出插入
类定义
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
|
#ifndef DATA_STRUCT_CIRCULAR_QUEUE_CIRCULAR_QUEUE_H #define DATA_STRUCT_CIRCULAR_QUEUE_CIRCULAR_QUEUE_H
#include <iostream>
using namespace std;
#endif
class CircularQueue { private: int * data; int capacity; int count; int head; int tail;
public: explicit CircularQueue(int capacity); CircularQueue(); [[nodiscard]] bool isFull() const; [[nodiscard]] bool isEmpty() const; void push(const int &); int peek() const; int pool(); void show() const; };
|
循环队列相关操作
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
|
#include "../header/queue_define.h"
CircularQueue::CircularQueue() : CircularQueue(20) {}
CircularQueue::CircularQueue(int capacity) { this->capacity = capacity; this->count = 0; this->head = 0; this->tail = 0; this->data = new int[capacity]; }
bool CircularQueue::isFull() const { return this->count == this->capacity && this->head == this->tail; }
bool CircularQueue::isEmpty() const { return this->count == 0; }
void CircularQueue::push(const int &value) { if (isFull()) { cout << "The queue is FULL" << endl; return; }
this->data[this->tail] = value; this->tail = (this->tail + 1) % this->capacity; this->count++; }
int CircularQueue::peek() const { return this->data[this->head]; }
int CircularQueue::pool() { if (isEmpty()) { cout << "The queue is EMPTY!!!" << endl; return -65535; }
int pool = this->data[this->head]; this->head = (this->head + 1) % this->capacity; this->count--;
return pool; }
void CircularQueue::show() const { int index = 1; cout << "index " << index << " -- value " << this->data[this->head] << endl; for (int i = this->head + 1; i != this->tail; i = (i + 1) % this->capacity, index++) { cout << "index " << index << " -- value " << this->data[i] << endl; } }
|
测试代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #include "../header/queue_define.h"
int main() { auto q = new CircularQueue(5); for (int i = 1; i <= 5; i++) { q->push(i); q->show(); cout << "==================" << endl; }
q->push(11); cout << "==================" << endl;
for (int i = 1; i <= 5; i++) { cout << "pop value " << q->pool() << endl; cout << "==================" << endl; }
cout << "pop value " << q->pool() << endl; return 0; }
|