zoukankan      html  css  js  c++  java
  • C++实现链式堆栈

    practice2.h文件

    #ifndef PRACTICE2_H_INCLUDED
    #define PRACTICE2_H_INCLUDED
    
    template<class T>  class LinkedStack;
    
    template<class T>
    class ChainNode//栈里面的每个节点
    {
        friend class LinkedStack<T>;
    private:
        T data;
        ChainNode<T> *link;
        ChainNode(const T& theData,ChainNode *n=0):data(theData),link(n)  {}
    
    };
    
    
    
    template<class T>
    class LinkedStack
    {
    public:
        LinkedStack():top(0)  {}
        ~LinkedStack() {MakeEmpty();}
        bool IsEmpty() const;
        T& Top() const;
        void Push(const T& e);
        void Pop();
        void MakeEmpty();
    private:
        ChainNode<T> *top;
    
    };
    
    template<class T>
    bool LinkedStack<T>::IsEmpty() const
    {
        return top==0;
    
    }
    
    template <class T>
    void LinkedStack<T> ::Push(const T &e)
    {
    
        top=new ChainNode<T>(e,top);
    }
    
    template <class T>
    T& LinkedStack<T>::Top() const
    {
      if(this->IsEmpty())
      {
          throw "Stack is Empty";
      }
      return top->data;
    }
    template<class T>
    void LinkedStack<T>::Pop()
    {
    
        if(this->IsEmpty())
            throw"is Empty";
        ChainNode<T> *delNode=top;
        top=top->link;
        delete delNode;//如果不删除的话会产生内存泄漏 和push的new对应
    }
    
    
    template<class T>
    void LinkedStack<T>::MakeEmpty()
    {
        while(!IsEmpty())
            Pop();
    }
    #endif // PRACTICE2_H_INCLUDED

    practice1.cpp

    #include<iostream>
    #include "practice2.h"
    using namespace std;
    
    int main()
    {
        LinkedStack<int> s;
    
        s.Push(10);
        cout<<s.Top()<<endl;
        s.Push(20);
        cout<<s.Top()<<endl;
          s.Pop();
         cout<<s.Top()<<endl;
    
        return 0;
    }
  • 相关阅读:
    POJ1064 浮点数二分答案
    2019牛客暑期多校训练营(第二场)H.Second Large Rectangle
    最大全1子矩阵的两种解法(例题:City Game HDU
    POJ
    Codeforces Round #588 (Div. 2) C
    1216E
    1221D
    BUY LOW, BUY LOWER, POJ
    Priest John's Busiest Day (2-sat)
    poj1080
  • 原文地址:https://www.cnblogs.com/libin123/p/10420129.html
Copyright © 2011-2022 走看看