手动实现顺序栈,要求实现数据结构中,所有栈的相关操作

#include <iostream>
#define MAXSIZE 10         //宏定义,栈的大小为10

using namespace std;

//定义一个模板类
template<typename T>
class MyStack
{
private:
    T data[MAXSIZE];                //栈内的数据元素
    int top=-1;                
public:
    //无参构造
    MyStack(){}
    //有参构造
    MyStack(T a):data(a)
    {
        cout<<"MyStack::有参构造"<<endl;
    }
    //析构函数
    ~MyStack(){}
    //判空
    bool MyStack_empty()
    {
        if(-1==top)
        {
            return false;
        }
        else
        {
            return true;
        }
    }

    //判满
    bool MyStack_full()
    {
       if(MAXSIZE-1==top)
       {
           return false;
       }
       else
       {
           return true;
       }
    }

    //入栈
    bool MyStack_push(T b)
    {
        if(top==MAXSIZE-1)
            return false;
        else
        {
            top++;                 //先加后压
            this->data[top]=b;
            return true;
        }
    }
    //出栈
    bool MyStack_pop()
    {
        if(-1==top)
            return false;
        else
        {
            cout<<"出栈元素为:"<<this->data[top]<<endl;
            top--;               //先弹后减
            return true;
        }
    }
    //遍历
    bool MyStack_output()
    {
        if(-1==top)
            return false;
        else
        {
            for(int i=0;i<=top;i++)
            {
                cout<<data[i]<<" ";
            }
            cout<<endl;
            return true;
        }
    }

};
int main()
{
    MyStack<int> M;        //必须显性调用
    M.MyStack_push(11);    //入栈
    M.MyStack_push(22);
    M.MyStack_push(33);
    M.MyStack_push(44);
    M.MyStack_push(55);
    M.MyStack_output();   //遍历
    M.MyStack_pop();      //出栈
    M.MyStack_output();   //遍历
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值