C++使用的类实现顺序栈

1、作业要求

        使用C++的类实现顺序栈。

2、实现过程

1)stack.h文件

#ifndef STACK_H
#define STACK_H

#define MAX 20

//定义顺序栈类
class Stack {
private:
    int* data;
    int top;
public:
    //创建顺序栈
    void stack_init();

    //判空
    bool stack_empty();

    //入栈
    void stack_push(int e);

    //遍历栈
    void stack_show();

    //出栈
    void stack_pop();

    //销毁
    void stack_delete();
};

#endif // STACK_H

2)stack.cpp文件

#include <iostream>
#include <stack.h>

using namespace std;

//申请空间
void Stack::stack_init() {
    data = new int[MAX];

    //初始化
    top = -1;
}

//判空
bool Stack::stack_empty(){
    return top == -1;
}

//入栈
void Stack::stack_push(int e){
    //入栈,先加后压
    top++;
    data[top] = e;
    cout << data[top] << " 入栈成功" << endl;
}

//遍历栈
void Stack::stack_show() {
    if(stack_empty()) {
        cout << "遍历失败" << endl;
    }
    for(int i=0; i<=top; i++) {
        cout << data[i] << "  ";
    }
    cout << endl;
}

//出栈
void Stack::stack_pop() {
    if(stack_empty()) {
        cout << "出栈失败" << endl;
    }
    //出栈,先弹后减
    cout << data[top] << " 出栈成功" <<endl;
    top--;
}

//销毁
void Stack::stack_delete() {
    delete []data;
    data=nullptr;
    cout << "销毁成功" << endl;
}

3)main.cpp文件

#include <iostream>
#include <stack.h>

using namespace std;

int main()
{
    Stack S1;
    S1.stack_init();

    //调用入栈函数
    S1.stack_push(3);
    S1.stack_push(8);
    S1.stack_push(9);
    S1.stack_push(6);
    S1.stack_push(5);

    //调用遍历函数
    S1.stack_show();

    //调用出栈函数
    S1.stack_pop();
    S1.stack_pop();
    //调用遍历函数
    S1.stack_show();

    //调用销毁函数
    S1.stack_delete();
    //调用遍历函数
    S1.stack_show();

    return 0;
}

3、效果截图

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值