1 >手动封装一个顺序栈类(数据元素为整形),要求私有成员属性:堆区空间的指针,用于存放数据,和一个指向栈顶元素的变量
main.cpp
#include "zuoye.h"int main()
{//实例化对象My_stack Stck;My_stack &st = Stck;//入栈Stck.My_pop(st);//出栈Stck.My_push(st);int key = Stck.My_get(st);cout << "栈顶元素 >>> " << key << endl;return 0;
}
head.h
#ifndef ZUOYE_H
#define ZUOYE_H#include <iostream>using namespace std;#define N 10class My_stack
{
private:int *ptr;int top;public:My_stack():ptr(new int [N]), top(-1) {cout << "顺序栈创建成功" << endl;}~My_stack() {delete []ptr;cout << "顺序栈退出成功" << endl;}//判空bool My_empty(My_stack &st);//判满bool My_full(My_stack &st);//入栈void My_pop(My_stack &st);//出栈void My_push(My_stack &st);//遍历void My_show(My_stack &st);//栈顶元素的引用int My_get(My_stack &st);
};#endif // ZUOYE_H
test.cpp
#include "zuoye.h"//判空
bool My_stack :: My_empty(My_stack &st){if(-1 == st.top){return true;}return false;
}
//判满
bool My_stack :: My_full(My_stack &st){if(N-1 == st.top){return true;}return false;
}
//入栈
void My_stack :: My_pop(My_stack &st){char ch = '\0';int key = 0;while(1){//入栈cout << " 是否入栈 Y/N >>> " ;cin >> ch;if(ch == 'Y' || ch == 'y'){cout << " 请输入要入栈的值 >>> " ;cin >> st.ptr[++(st.top)];}else{break;}//判满key = My_full(st);if(1 == key){cout << "栈满" << endl;break;}}My_show(st); //遍历
}void My_stack :: My_push(My_stack &st){bool key;char ch = 0;while(1){key = My_empty(st);//判空if(1 == key){cout << "栈空" << endl;break;}cout << " 是否出栈 Y/N >>>";cin >> ch;//出栈if(ch == 'Y' || ch == 'y'){cout << " 出栈的值为 >>>" << st.ptr[(st.top)--];}else{break;}}My_show(st); //遍历
}
//遍历
void My_stack :: My_show(My_stack &st){int i = 0;for(;i <= st.top ; i++){cout << st.ptr[i] << " ";}cout << endl;
}
//栈顶元素引用
int My_stack :: My_get(My_stack &st){return st.ptr[st.top];
}
2 >思维导图