栈的基本操作和实现C++模板类

来源:互联网 发布:单片机原理及应用pdf 编辑:程序博客网 时间:2024/06/01 08:47

1.基本概念

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

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

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

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

  栈的基本操作有:pop,push,判断空,获取栈顶元素,求栈大小
这里写图片描述
2.构造栈

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

  单向链表的头插法比较适合,链表头作为栈顶:
这里写图片描述
(1)节点的数据结构

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

(2)用C++模板类实现栈stack类

/*    A simple example for stack implemented by C++.*/template<class T>class myStack{protected:    struct node    {        T value;        node* next;        node() :next(nullptr){};        node(T t) :value(t), next(nullptr){};    };private:    int cnts; //入栈数量    node *head; //栈的头部public:    myStack(){ cnts = 0; head = new node; }    void stackPush(T arg); //入栈    T stackPop();  //出栈    T stackTop(); //获取栈顶元素    void printStack(); //打印栈    int counts(); //获取栈内元素个数    bool isEmpty(); //判断空};template<class T>void myStack<T>::stackPush(T arg){    node *pnode = new node(arg); //申请入栈元素的空间    pnode->next = head->next;    head->next = pnode;    cnts++;}template<class T>T myStack<T>::stackPop(){    if (head->next!=nullptr)     {        node* 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* 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;}

原文链接http://www.cnblogs.com/whlook/p/6531760.html

0 0