Appearance
手动封装一个循环顺序队列类:
- 私有成员属性:存放队列的数组、两个变量分别记录队头和队尾下标
- 公有成员函数:
- 入队(enqueue)
- 出队(dequeue)
- 展示(show)
- 求队列长度(size()):要求时间复杂度在常量级别
- 判满(bool full())
- 判空(bool empty())
cpp
#ifndef __CYCLE_QUEUE_H__
#define __CYCLE_QUEUE_H__
#define QUEUE_MAXSIZE 20
typedef int datatype;
class CycleQueue {
int _arr[QUEUE_MAXSIZE];
int _head_index = 0;
int _tail_index = 0;
public:
bool enqueue(datatype data); // 入队
bool dequeue(); // 出队
bool is_empty(); // 判断队列是否为空
bool is_full(); // 判断队列是否为满
int size(); // 获取队列中元素个数
void show(); // 显示队列中元素
};
#endifcpp
#include "CycleQueue.h"
#include <iostream>
int CycleQueue::size() {
return (_tail_index - _head_index + QUEUE_MAXSIZE) % QUEUE_MAXSIZE;
}
bool CycleQueue::is_empty() { return _head_index == _tail_index; }
bool CycleQueue::is_full() {
return (_tail_index + 1) % QUEUE_MAXSIZE == _head_index;
}
bool CycleQueue::enqueue(datatype data) {
if (is_full()) {
std::cout << "Queue is full!" << std::endl;
return false;
}
_arr[_tail_index] = data;
_tail_index = (_tail_index + 1) % QUEUE_MAXSIZE;
return true;
}
bool CycleQueue::dequeue() {
if (is_empty()) {
std::cout << "Queue is empty!" << std::endl;
return false;
}
_head_index = (_head_index + 1) % QUEUE_MAXSIZE;
return true;
}
void CycleQueue::show() {
if (is_empty()) {
std::cout << "Queue is empty!" << std::endl;
return;
}
int i = _head_index;
while (i != _tail_index) {
std::cout << _arr[i] << " ";
i = (i + 1) % QUEUE_MAXSIZE;
}
std::cout << std::endl;
}cpp
#include "CycleQueue.h"
#include <iostream>
using namespace std;
int main() {
CycleQueue q;
cout << "size: " << q.size() << endl;
cout << "isEmpyt: " << boolalpha << q.is_empty() << endl;
q.dequeue(); // fail
q.enqueue(3);
q.show();
cout << "size: " << q.size() << endl;
q.enqueue(5);
q.show();
cout << "size: " << q.size() << endl;
q.dequeue();
cout << "size: " << q.size() << endl;
q.show();
while (!q.is_full()) {
q.enqueue(8);
}
cout << "size: " << q.size() << endl;
q.show();
cout << "isFull: " << boolalpha << q.is_full() << endl;
q.dequeue();
q.enqueue(88);
q.show();
q.dequeue();
q.enqueue(77);
q.show();
q.enqueue(66); // fail
return 0;
}