7-18作业

7-18作业_第1张图片

#include

using namespace std;
class My_stack
{
private:
    int* ptr;         //执行堆区空间
    int top;
    int size; //记录栈顶元素

public:
    My_stack() :ptr(new int[10]), top(-1), size(10) {}

    //有参构造
    My_stack(int size) :ptr(new int[10]), top(-1), size(size) {};
    //析构函数
    ~My_stack()
    {
        delete[] ptr;
    }
    //判空函数
    bool pamkong()
    {
        return top == -1;
    }
    //判满函数
    bool panman()
    {
        return top == size - 1;
    }
    //入栈函数
    void ruzhan(int value)
    {
        if (panman())
        {
            cout << "manle" << endl;
            return;
        }
        top++;
        ptr[top] = value;
    }
    //出栈函数
    int chuzhan()
    {
        if (pamkong())
        {
            cout << "kongle" << endl;
            return -1;
        }
        int value = ptr[top];
        top--;
        return value;
    }
    //遍历栈
    // 
    void bianli()
    {
        if (pamkong())
        {
            cout << "wubianli" << endl;
            return;
        }
        for (int i = 0; i <= top; i++)
        {
            cout << ptr[i] << "   ";
        }
        cout << endl;
    }
    //获取栈顶元素的引用
    int& zhanding()
    {
        return ptr[top];
    }

};


int main()
{
    int num;
    My_stack p1;
    while (1)
    {
 
        puts("********0:退出");
        puts("********1:入栈");
        puts("********2:出栈");
        puts("********3:遍历");
        puts("********4:获取栈顶元素");
        puts("你需要那个功能:");
        cin >> num;
        switch (num)
        {
        case 1:
        {
            int br;
            cout << "输入入栈的元素:";
            cin >> br;
            p1.ruzhan(br);
            break;
        }
        case 2:
        {
            int rem = p1.chuzhan();
            if (rem==-1)
            {
                cout << "出栈失败" << endl;
            }
            cout << "出栈的元素是" << rem << endl;
            break;
        }
        case 3:
        {
            p1.bianli();
            break;
        }
        case 4:
        {
            int num = p1.zhanding();
            cout << "栈顶元素是:" << num << endl;
            break;
        }
        case 0:
        {
            cout << "退出成功" << endl;
            exit(0);
        }
        }
    }
	
	return 0;
}

 思维导图

7-18作业_第2张图片

 

 7-18作业_第3张图片

 

你可能感兴趣的:(c++)