C++类实现栈 析构 进出栈 清空栈
初学者的例子,有问题欢迎讨论
//stack.h /*************Stack.h*****************/ #include <iostream> #include <string> using namespace std; class Stack { public: Stack(int s) //构造s个数据栈 { size=s; data=new int[size]; if(data!=NULL) { top=data; cout<<"栈空间已成功建立!"<<endl; } } ~Stack() //析构函数 { if(data) { delete data; data=NULL; cout<<"栈空间释放!"<<endl; } } void pop(int num) //出栈 { cout<<num<<"出栈"<<endl; top--; if(top<data){ cout<<"已越过栈底!"<<endl; } } void push(int num) //进栈 { if(top-data>=size){ cout<<"栈空间不足!"<<endl; }else { top++; *top=num; cout<<num<<"进栈"<<endl; } } void clearStack() //清空栈 { top=data; } private: int *data; //栈数据存储首地址,栈底 int memNum; //栈元素个数 int size; //栈的大小 int *top; //栈顶指针 };
/*************Stack.h*****************/ #include <iostream> #include <string> using namespace std; class Stack { public: Stack(int s) //构造s个数据栈 { size=s; data=new int[size]; if(data!=NULL) { top=data; cout<<"栈空间已成功建立!"<<endl; } } ~Stack() //析构函数 { if(data) { delete data; data=NULL; cout<<"栈空间释放!"<<endl; } } void pop(int num) //出栈 { cout<<num<<"出栈"<<endl; top--; if(top<data){ cout<<"已越过栈底!"<<endl; } } void push(int num) //进栈 { if(top-data>=size){ cout<<"栈空间不足!"<<endl; }else { top++; *top=num; cout<<num<<"进栈"<<endl; } } void clearStack() //清空栈 { top=data; } private: int *data; //栈数据存储首地址,栈底 int memNum; //栈元素个数 int size; //栈的大小 int *top; //栈顶指针 };