数据结构--栈

#include<iostream>
using namespace std;

/*
栈:先进后出、后进向出,仅在表尾i而进行插入和删除操作的线性表。主要分为顺序栈(数组)、链栈(链表)
*/


class stack
{
private:
    int *date;
    int top; //top记录入栈元素的位置。top=0,表示入栈1个元素。top=-1表示空栈。top=size-1表示满栈
    const int size = 100;
public:
    stack():top(-1), date(new int[size]){} //构造函数-栈的初始化
    //入栈
    void push(const int &elm);
    //出栈
    void pop();
    //返回栈中的元素个数
    int stackLength();
    //若栈存在且非空,返回栈顶元素
    int GetTop();
    //若栈存在,则将栈清空
    void ClearStack();
    //判断栈是否为空
    bool isempty();
    //判断栈是否为满
    bool isFull();
    //遍历栈
    void ReadStack();
    ~stack();
};

stack::~stack()
{
    if(date != nullptr)
    {
        delete[] date;
        date = nullptr;
    }
}

void stack::push(const int &elm)
{
    //检查是否满栈,若满栈,则入栈错误,若没满,则执行插入
    if(isFull())
    {
        cout << "该栈已满" << endl;
        exit(0);
    }
    else
    {
        this->date[++top] = elm;
    }
    

}
void stack::pop()
{
    //判断该栈是否为空
    if(isempty())
    {
        cout << "空栈,无元素可出栈" << endl;
    }
    else
    {
        --this->top;
    }
    
}
int stack::stackLength()
{
    return this->top + 1;
}
int stack::GetTop()
{
    if (isempty())
    {
        cout << "空栈,栈顶无元素" << endl;
        return 0;
    }

    return this->date[top];
}
void stack::ClearStack()
{
    if (isempty())
    {
        cout << "空栈,无元素可清除" << endl;
    }
    else
    {
        this->top = -1;
    }
    
}
bool stack::isempty()
{
    return this->top == -1;
}
bool stack::isFull()
{
    return this->top == size - 1;
}
void stack::ReadStack()
{
    if (isempty())
    {
        cout << "空栈,无元素遍历" << endl;
    }
    else
    {
        for(int i = 0; i <= this->top; ++i)
        {
            cout << this->date[i] << " ";
        }
    }
    
    
}

void test()
{
    stack *s = new stack();
    s->push(1);
    s->push(2);
    s->push(3);
    s->push(4);
    s->push(5);
    s->pop();
    s->ReadStack();
    cout << endl;
    cout << s->stackLength() << s->GetTop() << endl;

}
int main()
{
    test();
    return 0;
}

输出:

1 2 3 4
44

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值