1用数组实现了栈的创建
2栈的遍历;
3压栈;
4出栈;
5栈是否为空
6栈是否满了
7删除栈
#include<iostream>
using namespace std;
class z{
private :
char *sz;
int zsize;
int ztop;
public: z(int size){
zsize=size;
sz=new char[zsize];
ztop=0;
}
~z(){
delete[] sz;
}
bool zEmpty(){
if(ztop==0)
return true;
else
return false;
}
bool zfull(){
if(ztop>=zsize-1){
return true;
}
else
return false;
}
void zclear(){
ztop=0;
}
bool push(char elem){
if(zfull()){
return false;
}
sz[ztop]=elem;
ztop++;
return true;
}
char pop(char elem){
if(zEmpty()){
return false;
}
ztop--;
elem=sz[ztop];
return elem;
}
void zTraverse(){
cout<<"遍历的结果";
for(int i=zsize-1;i>=0;i--){
cout<<sz[i]<<'\t';
}
}
};
int main(){
char c;
int zd;
cout<<"设置栈的长度"<<endl;
cin>> zd;
z *a=new z(zd);
for(int i=0;i<zd-1;i++){//因为压栈的时候头指针会向后多移一位,而数组大小是固定的,所以压栈时一是要考虑数组是从零开始,二是真正放进去的元素要比申请的内存小一;
cout<<"输出你要加的值 "<<endl;
cin >>c;
a->push(c);
}
if(a->zfull()){
cout<<"栈满了"<<endl;
}
a->zTraverse();
cout<<"使用压栈两次";
cout<<endl<<a->pop(c)<<endl;
cout<<endl<<a->pop(c)<<endl;
if(a->zEmpty()){
cout<<"栈为空"<<endl;
}
return 0;
}
运行截图: