7.18 作业 c++

 

#include <iostream>
#define MAXSIZE 10
using namespace std;

class my_stack
{
private:
    int *ptr;   //执行堆区空间
    int top;    //记录栈顶元素
public:
    my_stack():ptr(new int[10]),top(-1) {}
    
    //有参构造
    my_stack(int size,int t):ptr(new int[size]),top(t)
    {
        cout<<"my_stack::有参构造"<<endl;
    }
    //析构函数
    ~my_stack()
    {
        delete []ptr;
        cout<<"my_stack::析构构造"<<endl;
    }
    //判空函数
    bool empty();
    
    //判满函数
    bool full();
    
    //入栈函数
    int push();
    
    //出栈函数
    int pop();
    
    //遍历栈
    void output();
    
    //获取栈顶元素的引用
    int &gettop();
    
};
bool my_stack::empty()
{
    return top==-1;
}

bool my_stack::full()
{
    return top==MAXSIZE-1;
}

int my_stack::push()
{
    if(full())
    {
        cout<<"栈满"<<endl;
        return -1;
    }
    int num;
    cout<<"请输入想要插入的值:"<<endl;
    cin>>num;
    top++;
    return 0;
}

int my_stack::pop()
{
    if(empty())
    {
        cout<<"栈空"<<endl;
        return -1;
    }
    top--;
    return 0;
}

void my_stack::output()
{
    if(empty())
    {
        cout<<"栈空"<<endl;
        return;
    }
    for(int i=0;i<=top;i++)
    {
        cout<<*(ptr+i);
    }
    cout<<endl;
}

int &my_stack::gettop()
{
    if(empty())
    {
        cout<<"栈空"<<endl;
    }
    int &ref=*(ptr+top);
    return ref;
}

int main()
{
    my_stack str(MAXSIZE,-1);  //创建并初始化
    int num;
    cout<<"请输入要插入多少个元素:"<<endl;
    cin>>num;
    for(int i=0;i<num;i++)
    {
        str.push();
    }
    str.output();
    str.pop();
    cout<<"当前栈顶元素为:"<<str.gettop()<<endl;
    
    return 0;
}

思维导图:

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值