栈之顺序栈 C++代码实验

#include<iostream>
using namespace std;

#define DataType int
#define MaxSize 5                    //栈容量
typedef class
{
    DataType stack_data[MaxSize];
    int top=-1;                      //顺序栈只需要int型指示栈顶的位置下标
    public:
    void push(DataType data); 
    DataType pop();
    bool empty();
    int length();
    DataType gettop();              
}stack;

void stack::push(DataType data)
{
    if(stack::top==MaxSize-1)       //判断栈是否满了
    {
        cout<<"入栈失败(栈满)!"<<endl;
    }
    else
    {
        stack::stack_data[++stack::top]=data;   
        cout<<data<<" 入栈."<<endl;
    }
}

DataType stack::pop()
{
    if(stack::top==-1)             //判断栈是否为空
    {
        cout<<"出栈失败(栈空!)"<<endl;
        return -1;
    }
    DataType top_data = stack::stack_data[stack::top--];
    cout<<top_data<<" 出栈."<<endl;
    return top_data;
}
//根据栈顶位置判断栈是否为空
bool stack::empty()
{
    if(stack::top == -1)
    {
        cout<<"栈检查:空!"<<endl;
        return true;
    }
    cout<<"栈检查:非空!"<<endl;
    return false;    
}

int stack::length()
{
    cout<<"栈检查:数据个数为"<<stack::top+1<<endl;
    return stack::top+1;
}

DataType stack::gettop()
{
    if(stack::top==-1)
    {
        cout<<"读取栈顶元素失败(栈空!)"<<endl;
        return -1;
    }
    DataType top_num = stack::stack_data[stack::top];
    cout<<"栈顶元素为:"<<top_num<<endl;
    return top_num;
}
//测试
int main()
{
    stack s1;
    s1.push(1);
    s1.push(2);
    s1.push(3);
    s1.push(4);
    s1.push(5);
    s1.push(6);
    s1.length();
    s1.pop();
    s1.pop();
    s1.pop();
    s1.gettop();
    s1.pop();
    s1.pop();
    s1.pop();
    s1.empty();
}


运行结果:

附:栈之链式栈 C++代码实验

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值