#pragma once #include using namespace std; /************************************************************************ * Version : 1.0 * Date : 09 Jun 2017 * Description: 图模板类 /************************************************************************/ template class TGraphNode { public://methods inline TGraphNode(): mark(0){} inline ~TGraphNode(){} inline void SetValue(const T& val) { value = val; } inline T& GetValue(void) {return value;} inline void SetMark(int mk) {mark = mk; } inline int GetMark(void) {return mark; } list& GetPrev(void) {return m_prevNodes; } list& GetNext(void) {return m_nextNodes; } //清空所有前驱 inline void ClearPrev(void) { m_prevNodes.clear(); } //清空所有后继 inline void ClearNext(void) { m_nextNodes.clear(); } //增加一个前驱结点 inline bool AddPrevNode(TGraphNode* pNode) { if(0 == pNode) return false; if(find( GetPrev().begin(),GetPrev().end(),pNode ) != GetPrev().end() ) return true; this->GetPrev().push_back(pNode); pNode->GetNext().push_back(this); return true; } //增加一个后继结点 inline bool AddNextNode(TGraphNode* pNode) { if(0 == pNode) return false; if(find( GetNext().begin(),GetNext().end(),pNode ) != GetNext().end() ) return true; this->GetNext().push_back(pNode); pNode->GetPrev().push_back(this); return true; } //该结点是否有连接 inline bool hasLinkedNodes(void) { if(GetNext().empty() && GetPrev().empty() ) return false; return true; } //members private: T value; //数据体 int mark; //标记 list m_prevNodes; // 前驱结点list list m_nextNodes; //后继结点list }; template class TGraph { public: inline TGraph(void) {} inline ~TGraph(void) {DeepErase();} //清空结点 inline void Clear(void){m_graphNodes.clear(); } //彻底删除结点 inline void DeepErase(void) { //m_graphNodes.sort(); //m_graphNodes.unique(); typename list* >::iterator iter; for(iter = m_graphNodes.begin(); iter != m_graphNodes.end(); iter ++ ) delete *iter; m_graphNodes.clear(); } //添加一个新结点 inline void AddNode(TGraphNode* pNode, list*>* plstPrev = 0, list*>* plstNext = 0) { m_graphNodes.push_back(pNode); if(0 == plstPrev && 0 == plstNext) return; SetLink(pNode,plstPrev,plstNext); } //设置结点连接关系 inline void SetLink(TGraphNode* pNode, list*>* plstPrev , list*>* plstNext) { typename list*>::iterator iter; if(0 != plstPrev) { for(iter = plstPrev->begin(); iter != plstPrev->end(); iter ++ ) (*iter)->AddNextNode(pNode); } if(0 != plstNext) { for(iter = plstNext->begin(); iter != plstNext->end(); iter ++ ) (*iter)->AddPrevNode(pNode); } } inline int GetCount(void) {return m_graphNodes.size(); } ////给定初始点和判断函数,追踪出一条环状链路 //inline bool TraceCircle(TGraphNode* pStart, list* >& dstCircle, (TGraphNode*)Fun_NextNode(TGraphNode* pLast,TGraphNode* pCurrent) ) //{ // dstCircle.push_back(pStart); // TGraphNode* pLast = 0; // TGraphNode* pCurrent = pStart; // while(pCurrent = Fun_NextNode(pLast,pCurrent) ) // { // if(pCurrent == pStart) // return true; // dstCircle.push_back(pCurrent); // if(dstCircle.size() > m_graphNodes.size()+1) // return false; // } // return false; //} public: list* > m_graphNodes; //存储结点指针 };