场景说明:实现了了模板栈,但是调用的过程中,无法实现基本的功能:
声明如下:
template<class T>struct SNode { T t; SNode<T>* pNextNode; }; template<class T> class CStack { private: SNode<T>* m_pCStackTop; int m_nNodeCount; public: CStack(); ~CStack(); //进栈 int PushStack(T t); //获取栈顶元素 int GetTop(T& t); //出栈 int PopStack(T& t); int DisplayStack(); bool IsStackNotEmpty(); }; 定义如下: #include <stdio.h>#include <stdlib.h> #include <iostream> using namespace std; #include "stack.h" template<class T> CStack<T>::CStack() { //创建空头结点 m_pCStackTop=new SNode<T>; if(NULL==m_pCStackTop) { exit(-1); } m_pCStackTop->pNextNode=NULL; } template<class T> CStack<T>::~CStack() { SNode<T>* pTmpNode=m_pCStackTop; while(NULL!=pTmpNode) { m_pCStackTop=pTmpNode->pNextNode; delete pTmpNode; pTmpNode=m_pCStackTop; } } template<class T> int CStack<T>::PushStack(T t) { SNode<T>* pNewNode=new SNode<T>; pNewNode->t=t; if(NULL==pNewNode) { exit(-1); } pNewNode->pNextNode=m_pCStackTop->pNextNode; m_pCStackTop->pNextNode=pNewNode; return 0; } template<class T> int CStack<T>::GetTop(T &t) { if(NULL==m_pCStackTop->pNextNode) { return -1; } t=m_pCStackTop->pNextNode->t; return 0; } template<class T> int CStack<T>::PopStack(T &t) { if(NULL==m_pCStackTop->pNextNode) { return -1; } t=m_pCStackTop->pNextNode->t; SNode<T>* pTmpNode=m_pCStackTop->pNextNode; m_pCStackTop->pNextNode=pTmpNode->pNextNode; delete pTmpNode; return 0; } template<class T> int CStack<T>::DisplayStack() { SNode<T>* pTmpNode=m_pCStackTop->pNextNode; while((NULL!=pTmpNode)) { pTmpNode=pTmpNode->pNextNode; } } template<class T> bool CStack<T>::IsStackNotEmpty() { if(NULL!=m_pCStackTop->pNextNode) { return true; } return false; }
时间: 2024-10-31 00:56:43