手动封装一个循环顺序队列类
私有成员属性:存放队列的数组、两个变量分别记录队头和队尾下标
公有成员函数: 入队(push( type value ))
出队(pop())
展示(show)
求队列长度(size()):要求时间复杂度在常量级别
判满( bool full())
判空(bool empty())
#include <iostream>
using namespace std;
#define MAXSIZE 8
class stack
{
public:
void push(int value); //入队
void pop(); //出队
void output(); //遍历队列
bool full(); //判断队满
bool empty(); //判断队空
int size(); //求队列长度
private:
int arr[MAXSIZE]= {0};
int front = 0; //队头
int rear = 0; //队尾
};
//入队
void stack::push(int value)
{
if(full())
{
cout<<"队列已满"<<endl;
return ;
}
arr[rear] = value;
rear = (rear+1)%MAXSIZE;
}
//出队
void stack::pop()
{
if(empty())
{
cout<<"队列为空"<<endl;
return;
}
front = (front+1)%MAXSIZE;
}
//遍历队列
void stack::output()
{
if(empty())
{
cout<<"队列为空"<<endl;
return;
}
cout<<"遍历队列:"<<endl;
for(int i = front;i != rear;i = (i+1)%MAXSIZE )
{
cout<<arr[i] <<endl;
}
}
//判断队满
bool stack::full()
{
return (rear+1)%MAXSIZE == front ? true : false;
}
//判断队空
bool stack::empty()
{
return rear == front ? true : false;
}
//求队列长度
int stack::size()
{
return (MAXSIZE - front + rear)%MAXSIZE;
}
int main()
{
stack s1;//
int data; //存储输入数据
int n = 0; //存储数据个数
cout<<"输入数据个数"<<endl;
cin>>n;
//循环输入数据
for(int i = 0;i<n;i++)
{
cout<<"第"<<i+1<<"个数据:";
cin>>data;
s1.push(data);
}
//遍历数据
s1.output();
//队列长度
cout <<"队列长度 :"<<s1.size()<<endl;
//出队
s1.pop();
cout<<"出队后:"<<endl;
s1.output();
//出队后队列长度
cout <<"出队后队列长度 :"<<s1.size()<<endl;
return 0;
}