封装一个顺序栈

作业需求:

  1. 封装一个顺序栈,并封装其相应的操作:判空、入栈、出栈、遍历栈、销毁

实现过程:

1.头文件

#ifndef WORK01_H
#define WORK01_H
#include <iostream>
using namespace std;
class seqstack
{
    int *date;
    int top;

public:
    int size;
    void init();

    int empty();

    int full();

    void push(int e);

    void show();

    void pop();

    void free();

};
#endif // WORK01_H
  1. 源文件

#include <iostream>
#include<work01.h>
using namespace std;

    void seqstack::init()
    {
        date=new int[size];
        top=-1;

    }
    int seqstack::empty()
    {
        return top==-1;
    }
    int seqstack::full()
    {
        return top==size-1;
    }
    void seqstack::push(int e)
    {
        if(full())
        {
            cout <<"入栈失败"<<endl;
            return;
        }
        top++;
        date[top]=e;
        cout <<"入栈成功"<<endl;
    }
    void seqstack::show()
    {
        if(empty())
        {
           cout<<"遍历失败"<<endl;
           return;
        }
        cout<<"栈中从栈顶到栈底元素分别是:"<<endl;
        for(int i=top; i>=0; i--)
        {
            cout << date[i]<<" ";
        }
        cout<<endl;

    }
    void seqstack::pop()
    {
        if(empty())
        {
            cout<<"出栈失败"<<endl;

        }
        cout<<date[top]<<"出栈成功"<<endl;
        top--;
    }

    void seqstack::free()
    {
        delete date;
        date=nullptr;
        cout<<"销毁成功"<<endl;
    }

3.测试文件:

#include <iostream>
#include<work01.h>
using namespace std;

int main()
{
    seqstack q;
    q.size=20;
    q.init();
    if(q.empty())
    {
        cout<<"栈为空"<<endl;

    }else
    {
        cout<<"栈为非空"<<endl;
    }
    q.push(12);
    q.push(5);
    q.push(3);
    q.push(9);
    q.show();
    q.pop();
    q.show();
    q.free();
    return 0;
}

实现结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值