#include<iostream>
#include<string>
using namespace std;
class Stack{
private:
int base;
int rear;
int size;
int *data;
public:
Stack(int s)
{<span style="font-family: Arial, Helvetica, sans-serif;">//初始化栈</span>
this->size=s;
data=new int[size];
rear=0;
base=0;
}
virtual ~Stack()
{//栈的虚析构函数
delete []data;
}
bool isEmpty()
{//判栈空
return (base==rear);
}
bool isFull()
{//判栈满
return (size==rear);
}
void push(int num)
{//入栈
if(!isFull()){
data[rear++]=num;
cout<<num<<" was pushed!"<<endl;
}
else{
cout<<"The stack is full!"<<endl;
}
}
int pop()
{//出栈
if(!isEmpty()){
int popD=data[--rear];
size--;
cout<<"pop "<<popD<<"! Pre size:"<<size<<endl;
return popD;
}
else{
cout<<"The stack is Empty!"<<endl;
return -1;
}
}
void clear()
{//清空栈
size=0;
base=0;
rear=0;
cout<<"Pre size: "<<size<<" .You can input new data"<<endl;
}
void showStack()
{//打印栈中元素
int i=0;
for(;i<rear;i++)
cout<<i<<" data:"<<data[i]<<endl;
cout<<"Present size: "<<size<<endl;
}
};
int main()
{
int stackSize,inputD;
cout<<"Input the size of the stack:"<<endl;
cin>>stackSize;
Stack myStack(stackSize);
while((!myStack.isFull())){
cout<<"data:"<<endl;
cin>>inputD;
myStack.push(inputD);
}
myStack.showStack();
cout<<"pop:"<<myStack.pop()<<endl;
cout<<"pop:"<<myStack.pop()<<endl;
myStack.clear();
return 0;
}
c++栈类,以数组为存储结构。
最新推荐文章于 2023-03-04 13:29:46 发布