• C++:实现stack 类模板


    #include
    using namespace std;
    #define SIZE 20
    #define EMPTY_VAL -1
    typedef unsigned int uint32; 

    class Student
    {
    friend ostream& operator<<(ostream &out, const Student &s);
    public:
        Student()
        {
        }
        Student(string name, uint32 num, double grade)
        {
            s_name = name;
            s_num = num;
            s_grade = grade;
        }
    private:
        string s_name;
        uint32 s_num;
        double s_grade;
    };

    ostream& operator<<(ostream &out, const Student &s)
    {
        out << "name:" << s.s_name << " num: " << s.s_num << " grade: "<< s.s_grade;
        return out;
    }

    template
    class MyStack
    {
    public:
        MyStack();
        ~MyStack();
        void Push(T data);
        T Visit();
        T Pop();
        int GetStackLen();
    private:
        T *s_ptr;
        uint32 s_size;
        int s_top;
    };

    template
    MyStack::MyStack()
    {
        this->s_ptr = new T[SIZE];
        this->s_size = SIZE;
        this->s_top = EMPTY_VAL;
    }

    template
    MyStack::~MyStack()
    {
        if(s_ptr != NULL)
        {
            delete [] s_ptr;
            s_ptr = NULL;
        }
    }

    template
    void MyStack::Push(T data)
    {
        /*is full?*/
        s_top++;
        s_ptr[s_top] = data;
    }

    template
    T MyStack::Pop()
    {
        /*is empty?*/
        T temp_data = s_ptr[s_top];
        s_top--;
        return temp_data;
    }

    template
    T MyStack::Visit()
    {
        /*is empty?*/
        return s_ptr[s_top];
    }

    template
    int MyStack::GetStackLen()
    {
        return s_top + 1;
    }

    void test01()
    {
        MyStack s1;
        s1.Push(2);
        s1.Push(16);
        s1.Push(89);

        int p_data = s1.Pop();
        cout << "data: " << p_data << endl;
        p_data = s1.Pop();
        cout << "data: " << p_data << endl;
    }

    void test02()
    {
        MyStack s1;
        s1.Push("**");
        s1.Push("KunKun");
        s1.Push("LOVE");
        s1.Push("I");
        
        int len = s1.GetStackLen();
        for(int i = 0; i < len; i++)
        {
            cout << s1.Pop() << endl;
        }
    }

    void test03()
    {
        MyStack s1;
        s1.Push(Student("zs", 4, 56.7));
        s1.Push(Student("ls", 7, 58.7));
        s1.Push(Student("ww", 3, 98.7));

        Student s_data = s1.Pop();

        cout << s_data << endl;
    }

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

  • 相关阅读:
    广州蓝景分享—程序员在面试时必须要做的五件事,最后一件很重要
    2023/10/24 MySQL学习
    RHCE——二十、Ansible及安装与配置
    IDEA运行项目报错:Command line is too long的解决办法
    猿创征文|嵌入式系统应用开发工具链必备
    为华生物NH2-PEG-NH2氨基聚乙二醇氨基的简介及应用说明
    Java封装
    Android 控件保持宽高比得几种方式
    LeetCode100122. Separate Black and White Balls
    shell脚本之免交互
  • 原文地址:https://blog.csdn.net/qq_63626307/article/details/126823745