定义一个Mystack类实现栈的基本功能

用vector:

#include <vector>
#include <iostream>
using namespace std;

class Mystack{
public:
    Mystack(){ //写一个栈的构造函数,vec+idx来标记
        top_idx=0;
        data.push_back(-1);
    }

    bool empty(){
        if(data[top_idx]==-1){
            return true;
        }
        return false;
    }
    void push(int x){ //填入元素,栈顶坐标后移
        data.push_back(x);
        top_idx++;
    }
    void pop(){ //弹出元素,栈顶坐标前移
        data.pop_back();
        top_idx--;
    }
    int top(){ //取栈顶元素
        return data[top_idx];
    }
private:
    int top_idx ;
    vector<int> data;


};


int main(){
    Mystack s;
    cout<<"-------1 represent the the stack is empty-------"<<endl;
    cout<<s.empty()<<endl;
    vector<int> vec{1,23,4,5,6};
    for(int i=0;i<vec.size();++i){
        s.push(vec[i]);
    }
    cout<<"-------from the top of the stack-------"<<endl;
    while(!s.empty()){
        cout<<s.top()<<endl;
        s.pop();
    }
    system("pause");
    return 0;
}

不用vector,用数组

#include <iostream>
using namespace std;

struct Mystack{

    void InitStack(){
        TOP = -1;
    }


    void clear(){
        TOP = -1;
    }

    int size1() {
        return TOP+1;
    }
    bool empty(){
        if(TOP == -1) return true;
        else return false;
    }

    //栈满不能push
    void push(int x) {
        //if()
        st[++TOP] = x;
    }

    void pop(){
        TOP--;
    }
    //栈空取顶报错
    int top(){
        //if()
        return st[TOP];
    }

private:
    int st[10];
    int TOP ;
};


int main()
{
    Mystack stc;
    stc.InitStack();
    //int m;
   for(int i=0; i<10 ;i++)
    {
        stc.push(i);
        //cin >> m;
    }
   cout <<stc.top()<<endl;
   cout << stc.size1();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值