• 自定义模板动态数组栈


    Stack.hpp

    #ifndef MYSTACK_H
    #define MYSTACK_H
    
    template<class T>
    class Stack
    {
    public:
        Stack(int len = 10)
        {
            this->size = len;
            this->top = -1;
            stackPtr = new T[len];
        }
        
        ~Stack()
        {
            if (stackPtr != nullptr)
            {
                delete[] stackPtr;
            }
    
        }
    
        void push(const T& st)
        {
            if (isFull())
            {
                cout << "栈已满" << endl;
                //exit(1);
            }
            else
            {
                this->stackPtr[++top] = st;
            }
        }
    
        void pop()
        {
            if (this->top == -1)
            {
                cout << "空栈" << endl;
                //exit(1);
            }
            else
            {
                this->stackPtr[this->top--] = 0;
            }
    
        }
    
        int getSize()
        {
            return this->top+1;
        }
    
        void print()
        {
            for (int i = 0; i < this->top+1; i++)
            {
                cout << stackPtr[i] << " ";
            }
            cout <<"-----------------------"<< endl;
        }
        int isEmpty()const { return top == -1; }
        int isFull()const { return top == size - 1; }
    
        /*T& operator[](int index)
        {
            return this->stackPtr[index];
        }*/
    
    private:
        int size; //栈中元素个数
        int top;//栈顶位置
        T* stackPtr;//保存动态数组指针
    };
    #endif

    Test.cpp

    void Test03()
    {
        Stack<int> st(8);
        st.push(1);
        st.push(3);
        st.push(5);
        st.push(7);
        st.push(9);
        cout << "stack size: " << st.getSize() << endl;
        st.print();
        st.pop();
        cout << "stack size: " << st.getSize() << endl;
        st.print();
        st.push(100);
        st.push(1000);
        cout << "stack size: " << st.getSize() << endl;
        st.print();
    
        st.pop();
        st.pop();
        st.pop();
        st.pop();
        st.pop();
        st.pop();
        st.pop();
        cout << "stack size: " << st.getSize() << endl;
        st.print();
    
        Stack<char> st1(5);
        st1.push('a');
        st1.push('b');
        st1.push('c');
        st1.push('d');
        st1.push('e');
        st1.push('f');
        cout << "stack size: " << st1.getSize() << endl;
        st1.print();
    }
  • 相关阅读:
    nil指针判断
    不使用slice作为函数入参
    log4php
    Results gofmt 0% go_vet 100% gocyclo 97% golint 100% ineffassign 97% license 100% misspell 100%
    获取点击元素的文本信息 复制到剪切板 监听鼠标悬浮
    磁盘IO
    copylocks
    sh: 1: node: Permission denied
    白盒代码审计
    升级基础
  • 原文地址:https://www.cnblogs.com/mmc9527/p/10455357.html
Copyright © 2020-2023  润新知