手动封装一个循环顺序队列类(Stack)
私有成员属性:存放队列的数组、两个变量分别记录队头和队尾下标
公有成员函数: 入队(push( type value ))
出队(pop())
展示(show)
求队列长度(size()):要求时间复杂度在常量级别
判满( bool full())
判空(bool empty())
运行结果
代码
#include <iostream>
#define MAXSIZE 5
using namespace std;
class Stack
{
private:
int data[MAXSIZE];
int front = 0;
int rear = 0;
public:
//判空
bool empty()
{
return front == rear;
}
//判满
bool full()
{
return front == (rear+1)%MAXSIZE;
}
//入队
void push(int e)
{
if(full()){
cout<<"入队失败"<<endl;
return;
}
data[rear]=e;
rear=(rear+1)%MAXSIZE;
}
//出队
void pop()
{
if(empty()){
cout<<"出队失败"<<endl;
return;
}
cout<<"出队的元素是:"<<data[front]<<endl;
front=(front+1)%MAXSIZE;
}
//遍历
void show()
{
if(empty()){
cout<<"遍历失败"<<endl;
return;
}
for(int i=front;i!=rear;i=(i+1)%MAXSIZE){
cout<<data[i];
}
cout<<endl;
}
//个数
int mySize()
{
return (MAXSIZE-front+rear)%MAXSIZE;
}
};
int main()
{
int e;
string s;
Stack s1;
while(1){
cout<<"输入要入队的元素:";
cin>>e;
s1.push(e);
cout<<"要继续吗?yes/no :";
cin>>s;
if(s == "no"){
break;
}
}
s1.pop();
s1.show();
int count = s1.mySize();
cout<<"个数为:"<<count<<endl;
return 0;
}