9.25C++(day6)

#include <iostream>

using namespace std;

class my_stack
{
private:
    int * data;
    int size;
    int top;
public:
    my_stack(){}
    my_stack(int size):size(size),top(-1)
    {
        data = new int[size];
    }
    ~my_stack(){}
    my_stack & operator=(const my_stack &other)
    {
        if(this!=&other)
        {
            this->data = other.data;
        }

        return *this;
    }
    void push(int value)
    {
        if(top>=size-1)
        {
            cout<<"栈满"<<endl;
        }
        this->top++;
        data[top] = value;
    }
    void pop()
    {
        if(top==-1)
        {
            cout<<"栈空"<<endl;
        }
        cout<<"删除栈顶元素:"<<this->data[top]<<endl;
        this->top--;
    }
    void get_top()
    {
        cout<<"此时的栈顶元素:"<<this->data[top]<<endl;
    }
    bool empty()const
    {

        return top+1;
    }
    int get_size()//返回元素数
    {
        return this->top+1;
    }
    void swap(my_stack & other)
    {
        int * temp;
        temp = data;
        data = other.data;
        other.data = temp;
    }
};
int main()
{
    my_stack s1(10);
    cout<<"容纳的元素数:"<<s1.get_size()<<endl;
    s1.push(1);
    s1.push(9);
    cout<<"容纳的元素数:"<<s1.get_size()<<endl;
    s1.get_top();//9
    s1.pop();
    s1.get_top();//1
    s1.pop();
    if(s1.empty()){
        cout<<"栈不为空"<<endl;
    }else{
        cout<<"栈为空"<<endl;
    }
    s1.push(10);
    s1.push(14);
    s1.push(8);
    s1.get_top();
    cout<<"容纳的元素数:"<<s1.get_size()<<endl;
    my_stack s2(10);
    s2.push(999);
    s2.swap(s1);
    s2.get_top();

    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值