我們今天將會為大家詳細介紹一下有關C++鏈棧模板的基本操作方法。希望剛剛基礎這款語言的朋友們可以通過對這篇文章的解讀,充分的掌握這方面的應用技巧,以方便我們在實際應用中熟練應用。
C++鏈棧模板聲明
- template <class T>
- struct StackNode
- {
- T typeData;
- StackNode *nextNode;
- };
- template <class T>
- class DZ_Stack
- {
- public:
- bool Push(const T data);
- bool Pop(T& data);
- bool Peek(T& data);
- bool IsEmpty();
- DZ_Stack();
- virtual ~DZ_Stack();
- private:
- StackNode<T> *pStackTop;
- int iNodeCount;
- };
C++鏈棧模板實現
- template <class T>
- DZ_Stack<T>::DZ_Stack()
- {
- pStackTop=NULL;
- iNodeCount=0;
- }
- template <class T>
- DZ_Stack<T>::~DZ_Stack()
- {
- while(!IsEmpty())
- {
- StackNode<T> *pStackNode= pStackTop;
- pStackToppStackTop=pStackTop->nextNode;
- delete (pStackNode);
- pStackNode=NULL;
- }
- pStackTop=NULL;
- }
- template <class T>
- bool DZ_Stack<T>::Push(const T data)
- {
- StackNode<T> *pStackNode=new StackNode<T>;
- if( NULL == pStackNode )
- return false;
- pStackNode->typeData=data;
- pStackNode->nextNode=pStackTop;
- pStackTop=pStackNode;
- iNodeCount++;
- return true;
- }
- template <class T>
- bool DZ_Stack<T>::Pop(T& data)
- {
- if ( IsEmpty() )
- return false;
- data=pStackTop->typeData;
- StackNode<T> *pStackNode= pStackTop;
- pStackToppStackTop=pStackTop->nextNode;
- delete (pStackNode);
- iNodeCount--;
- return true;
- }
- template <class T>
- bool DZ_Stack<T>::Peek(T& data)
- {
- if (IsEmpty())
- return false;
- data=pStackTop->typeData;
- return true;
- }
- template <class T>
- bool DZ_Stack<T>::IsEmpty()
- {
- if ( NULL == pStackTop )
- return true;
- else
- return false;
- }
- #endif // !defined(AFX_DZ_STACK_H__10036803_D752_4EF7_
852D_DD6B377D7AB9__INCLUDED_)
以上就是對C++鏈棧模板的相關介紹。