1.封装顺序栈,实现入栈,出栈,遍历,判断等功能
#include <iostream>
#include <string.h>
using namespace std;
//typedef int datatype;
typedef struct{
int data[10];
int top;
}stacks;
class My_stack{
private:
int *ptr; //执行堆区空间
int top; //记录栈顶元素
public:
//有参构造
My_stack(int size,int t):ptr(new int[5]),top(-1) //参数列表后由冒号引出
{
}
//析构函数
~My_stack(){
delete []ptr; //把new的那片空间释放掉,不用内存泄漏
}
bool fudge_empty();
bool fudge_full();
int push(int data);
int pop();
int output();
};
//判空函数
bool My_stack::fudge_empty(){
if(top==-1){
return true;
}
}
//判满函数
bool My_stack::fudge_full(){
if(top==5){
return true;
}
}
//入栈函数
int My_stack::push(int data){ /*int *ptr,int top,
成员函数所有的成员变量都可以用的
不用传参,直接拿过来用 */
*(ptr+(top+1)) = data;
top++;;
}
//出栈函数
int My_stack::pop(){
if(fudge_empty()==1){
cout<<"栈空,wrong!"<<endl;
}else{
top--;
}
return 0;
}
//遍历栈
int My_stack::output(){
if(fudge_empty()==1){
cout<<"栈空,wrong!"<<endl;
}else{
for(int i=0;i<top;i++){
cout<<*(ptr+i)<<endl;
}
}
}
//获取栈顶元素的引用
//cout << "Hello World!" << endl;
int main()
{
My_stack m1(5,-1); //定义一个变量并初始化,用这个变量去调用成员函数
int data;
//
cout<<"请入栈"<<endl;
if(m1.fudge_empty()==0){
cout<<"栈满,wrong!"<<endl;
}else{
for(int i=0;i<5;i++){
cout<<""<<endl;
cin>>data;
while(getchar()!='\n') ; //按了回车就跳出循环;没有按回车的时候,就一直卡在那
m1.push(data);
}
//遍历
m1.output();
}
//
cout<<"请出栈" <<endl;
if(m1.fudge_full()==0){
cout<<"栈空,wrong!"<<endl;
}else{
while(getchar()=='p'){
m1.pop();
}
}
return 0;
}