手动封装一个循环顺序队列类(Stack)
私有成员属性:存放队列的数组、两个变量分别记录队头和队尾下标
公有成员函数: 入队(push( type value ))
出队(pop())
展示(show)
求队列长度(size()):要求时间复杂度在常量级别
判满( bool full())
判空(bool empty())
#include <iostream>
using namespace std;
class Stack
{
int *p=new int[8]{1,2,3,4,5,6,7};
int front=p[0];
int rear=p[7];
public:
int push(int m)
{
if(Stack::full()==0)
return -1;
else
{
cout<<"入队的元素是:"<<m<<endl;
this->rear=m;
this->rear=(this->rear+1)%8;
return 0;
}
}
int pop()
{
if(Stack::empty()==0)
return -1;
else
{
cout<<"出队的元素是:"<<this->front<<" ";
this->front=(this->front+1)%8;
return 0;
}
}
void show()
{
if(Stack::empty()==0)
return;
else
{
for(int i=0;i<8;i++)
{
cout<<p[i]<<" ";
}
cout<<"长度为"<<size()<<endl;
}
}
int size()
{
int len=0;
for(int i=0;i<8;i++)
{
len+=sizeof(p[i]);
}
return len;
}
bool full()
{
if(p==NULL||this->front==(this->rear+1)/8)
{
cout<<"队列已满"<<endl;
}
return -1;
}
bool empty()
{
if(p==NULL||(this->front==this->rear))
{
cout<<"队列为空"<<endl;
}
return -1;
}
};
int main()
{
Stack q;
q.push(7);
q.show();
q.pop();
q.show();
return 0;
}