流程图:
手动封装一个顺序栈类(数据元素为整形),要求私有成员属性:堆区空间的指针,用于存放数据,和一个指向栈顶元素的变量
class My_stack { private: int *ptr; //执行堆区空间 int top; //记录栈顶元素 public: My_stack():ptr(new int[10]), top(-1) {} //有参构造 My_stack(int size){}; //析构函数 //判空函数 //判满函数 //入栈函数 //出栈函数 //遍历栈 //获取栈顶元素的引用 };
作业代码:
#include <iostream> #include <cstring> #define MAXSIZE 20 using namespace std; class stack { private: int *ptr; //执行堆区空间 int top; //记录栈顶元素 public: //有参构造 stack(int size,int t):ptr(new int[size]),top(t) { cout<<"stack::有参构造"<<endl; } //析构函数 ~stack() { delete []ptr; } //判空函数 int empty() { if(top==-1) { cout<<"栈空"<<endl; return -1; } return 0; } //判满函数 int null() { if(top==MAXSIZE-1) { cout<<"栈满"<<endl; return -1; } return 0; } //入栈函数 int push(int num) { int res=null(); if(res<0) { cout<<"栈满入栈失败"<<endl; return -1; } else { ptr[top+1]=num; top++; } return 0; } //出栈函数 int pop() { int res=empty(); if(res<0) { cout<<"栈空出栈失败"<<endl; return -1; } else { top--; } return 0; } //遍历栈 void output() { int res = empty(); if(res<0) { cout<<"栈空"<<endl; return; } for(int i=0;i<top;i++) { cout<<ptr[i]; } cout<<endl; } //获取栈顶元素的引用 int gettop() { int res = empty(); if(res<0) { cout<<"栈空"; return -1; } int &ref = ptr[top]; return ref; } }; int main() { stack sp(MAXSIZE,-1); int num=0; for(int i=0;i<5;i++) { cout<<"请入栈:"<<endl; cin>>num; sp.push(num); } cout<<"栈内元素为:"<<endl; sp.output(); while(1) { cout<<"确定要出栈吗?y/n"<<endl; if(getchar()=='y'||'Y') { sp.pop(); } else if(getchar()=='n'||'N') break; while(getchar()!='\n'); cout<<"栈内元素为:"<<endl; sp.output(); } cout<<"栈顶元素的引用为"<<endl; cout<<sp.gettop()<<endl; return 0; }