手动封装一个循环顺序队列类
私有成员属性:存放队列的数组、两个变量分别记录队头和队尾下标
公有成员函数: 入队(push( type value ))
出队(pop())
展示(show)
求队列长度(size()):要求时间复杂度在常量级别
判满( bool full())
判空(bool empty())
#include<iostream>
using namespace std;
#define ERR_MSG(MSG) do{ \
cout<<"line:"<<__LINE__<<":"<<MSG; \
}while(0);
#define MAX_SIZE 7 //MAX_SIZE-1是队列最多能存放的数据个数
class queue_cir
{
public:
void push(int value);
void pop(void);
void show(void);
int size(void);
bool full(void);
bool empty(void);
private:
int queue[MAX_SIZE] = {0};
int head = 0, rear = 0;
};
//入队
void queue_cir::push(int value)
{
cout<<"push():"<<endl;
if (full())
{
ERR_MSG("push:队列已满,不可入队\n");
return ;
}
queue[rear] = value;
rear = (rear+1)%MAX_SIZE;
}
//出队
void queue_cir::pop(void)
{
cout<<"pop():"<<endl;
if (empty())
{
ERR_MSG("pop:队列已空,不可出队\n");
return ;
}
cout<<queue[head]<<" was popped"<<endl;
head = (head+1)%MAX_SIZE;
}
//遍历输出
void queue_cir::show(void)
{
cout<<"data remaining:";
if (empty())
{
ERR_MSG("show:队列为空\n");
return ;
}
int head_n = head;
while((head_n) != rear)
{
cout<<queue[head_n]<<" ";
head_n = (head_n+1)%MAX_SIZE;
}
cout<<endl;
}
//输出队列大小
int queue_cir::size(void)
{
//如果head大于read,需要将rear加上MAX_SIZE再减去head
return (head<rear) ? rear-head : rear+MAX_SIZE-head;
}
//队列判满
bool queue_cir::full(void)
{
//队列满的状态是队尾+1等于队头
return (rear+1)%MAX_SIZE == head ? true : false;
}
//队列判空
bool queue_cir::empty(void)
{
//队列空的状态是队尾等于队头
return rear == head ? true : false;
}
int main(int argc, char const *argv[])
{
queue_cir q1;
//push测试
cout<< (q1.empty() ? "queue empty":"queue full")<<endl;
q1.pop();
int j = 30;
for(int i = 0; i<7; i++)
{
cout<<q1.size()<<" data remaining"<<endl;
q1.push(j--);
q1.show();
}
//pop测试
cout<< (q1.full() ? "queue full":"queue empty")<<endl;
for(int i = 0; i<7; i++)
{
q1.pop();
q1.show();
}
return 0;
}