手动封装一个循环顺序队列类(Stack)
私有成员属性:存放队列的数组、两个变量分别记录队头和队尾下标
公有成员函数: 入队(push( type value ))
出队(pop())
展示(show)
求队列长度(size()):要求时间复杂度在常量级别
判满( bool full())
判空(bool empty())
#include <iostream>
#define MAXSIZE 10
typedef int datatype;
using namespace std;
class Stack
{
private:
datatype arr[MAXSIZE];
int head=0;
int rear=0;
public:
//判满
bool full()
{
return (rear+1)%MAXSIZE==head;
}
//判空
bool empty()
{
return head==rear;
}
//队长
int size()
{
return (rear-head+MAXSIZE)%MAXSIZE;
}
//出队
void pop()
{
if(empty())
{
cout<<"empty"<<endl;
}
else
{
head=(head+1)%MAXSIZE;
}
}
//入队
void push(datatype value)
{
if(full())
{
cout<<"full"<<endl;
}
else
{
arr[rear]=value;
rear=(rear+1)%MAXSIZE;
}
}
//展示
void show()
{
cout<<"遍历结果为:"<<endl;
for(int i=head;i!=rear;i=(i+1)%MAXSIZE)
{
cout<<arr[i]<<endl;
}
}
};
int main()
{
Stack s;
s.push(1);
s.push(2);
s.push(3);
s.pop();
s.show();
int s_size=s.size();
cout<<"队长:"<<s_size<<endl;
return 0;
}