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 10
class 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 >思维导图