• C++:栈(stack)的模板类实现


    1.基本概念

      栈中的元素遵守“先进后出”的原则(LIFO,Last In First Out)

      只能在栈顶进行插入和删除操作

      压栈(或推入、进栈)即push,将数据放入栈顶并将栈顶指针加一

      出栈(或弹出)即pop,将数据从栈顶删除并将栈顶指针减一

      栈的基本操作有:poppush判断空获取栈顶元素求栈大小

      

    2.构造栈

      可以使用数组构造栈,也可以使用单向链表构造,我觉得使用单向链表更加灵活方便,下面的例子我使用单向链表来构造栈。

      单向链表的头插法比较适合,链表头作为栈顶:

      节点的数据结构:

    template<class T>
    struct node
    {
        T value;  //储存的值
        node<T>* next; 
    
        node() :next(nullptr){} //构造函数
        node(T t) :value(t), next(nullptr){}
    };

      用模板类构造一个简单的stack类:

    template<class T>
    class myStack
    {
        int cnts; //入栈数量
        node<T> *head; //栈的头部
    public:
    
        myStack(){ cnts = 0; head = new node<T>; }
        void stackPush(T arg); //入栈
        T stackPop();  //出栈
        T stackTop(); //获取栈顶元素
    
        void printStack(); //打印栈
        int counts(); //获取栈内元素个数
        bool isEmpty(); //判断空
    };
    template<class T>
    void myStack<T>::stackPush(T arg)
    {
        node<T> *pnode = new node<T>(arg); //申请入栈元素的空间
        pnode->next = head->next;
        head->next = pnode;
        cnts++;
    }
    template<class T>
    T myStack<T>::stackPop()
    {
        if (head->next!=nullptr) 
        {
            node<T>* temp = head->next;
            head->next = head->next->next;
            T popVal = temp->value;
            delete temp;
            return popVal;
        }
    }
    template<class T>
    T myStack<T>::stackTop()
    {
        if (head->next!=nullptr)
        {
            return head->next->value;
        }
    }
    template<class T>
    void myStack<T>::printStack()
    {
        if (head->next != nullptr)
        {
            node<T>* temp = head;
            while (temp->next != nullptr)
            {
                temp = temp->next;
                cout << temp->value << endl;
            }
        }
    }
    template<class T>
    int myStack<T>::counts()
    {
        return cnts;
    }
    template<class T>
    bool myStack<T>::isEmpty()
    {
        if (cnts)
            return false;
        else
            return true;
    }

    GitHub:https://github.com/whlook/stackTemplate

       

    ------------ 转载请注明出处 ------------
  • 相关阅读:
    Day 03--设计与完善(一)
    Day 02--选题与设计(二)
    Day 01--选题与设计(一)
    课程设计第六天,08.24
    课程设计第五天,08.23
    课程设计第四天,08.22
    课程设计第三天,08.21
    软件课程设计第二天,08.20
    软件课程设计第一天
    旋转正方形
  • 原文地址:https://www.cnblogs.com/whlook/p/6531760.html
Copyright © 2020-2023  润新知