1.手动封装一个顺序栈类(数据元素为整形),要求私有成员属性:堆区空间的指针,用于存放数据,和一个指向栈顶元素的变量;
---main.cpp---主函数
#include "stack.h"
int main()
{
int size;
cout<<"输入栈大小>>> ";
cin>>size;
My_stack sta(size); //调用有参构造
char ch;
int elem;
do //入栈
{
cout<<"输入入栈元素>>> ";
cin>>elem;
sta.my_push(size,elem);
if(sta.my_full(size) == true)
break;
cout<<"继续入栈? y/Y ";
cin>>ch;
}while(ch == 'y' || ch =='Y');
sta.my_loop(); //遍历栈
cout<<"栈顶元素>>> "<<sta.get_top()<<endl;; //获取栈顶元素
cout<<"删除两个元素后---"<<endl;
sta.my_pop(); //出栈
sta.my_pop();
sta.my_loop(); //遍历栈
cout<<"栈顶元素>>> "<<sta.get_top()<<endl; //获取栈顶元素
return 0;
}
---stack.h---头文件
#ifndef STACK_H
#define STACK_H
#include <iostream>
using namespace std;
class My_stack
{
private:
int *ptr; //指向堆区空间
int top; //记录栈顶元素
public:
My_stack():ptr(new int[10]),top(-1){} //无参构造
My_stack(int size):ptr(new int[size]),top(-1){} //有参构造
~My_stack(){delete [] ptr;}
bool my_empty(); //判空函数
bool my_full(int size); //判满函数;
void my_push(int size,int elem); //入栈函数
void my_pop(); //出栈//出栈函数
void my_loop(); //遍历栈
int get_top(); //获取栈顶元素
};
#endif // STACK_H
---stack.cpp---实现函数
#include "stack.h"
bool My_stack::my_empty() //判空
{
return top == -1;
}
bool My_stack::my_full(int size) //栈满
{
return top == (size-1);
}
void My_stack::my_push(int size,int elem) //入栈
{
if(!my_full(size))
ptr[++top] = elem;
else
{
cout<<"栈满"<<endl;
return;
}
}
void My_stack::my_pop() //出栈
{
if(!my_empty())
top--;
else
{
cout<<"栈空"<<endl;
return;
}
}
void My_stack::my_loop() //遍历
{
if(!my_empty())
{
for(int i=top; i>=0; i--)
{
cout<<ptr[i]<<" ";
}
cout<<endl;
}
}
int My_stack::get_top() //获取栈顶元素
{
if(!my_empty())
return ptr[top];
}
2.今日脑图