C++:手动封装一个顺序栈类(数据元素为整形),要求私有成员属性:堆区空间的指针,用于存放数据,和一个指向栈顶元素的变量

 流程图:

手动封装一个顺序栈类(数据元素为整形),要求私有成员属性:堆区空间的指针,用于存放数据,和一个指向栈顶元素的变量

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值