C++图:极简版的图类(邻接链表)

来源:互联网 发布:龙虎榜数据分析软件 编辑:程序博客网 时间:2024/06/01 09:14

建立一个(极简版的)图类(邻接链表)。

该图类是通过一个极简版的单向链表类  修改得到的。

代码如下:


图类头文件

//graph.h//边struct Edge{int startVertex;int endVertex;int weightEdge;//边的权重Edge * nextEdge;Edge(int s, int e, int w):startVertex(s),endVertex(e),weightEdge(w),nextEdge(NULL){}};//节点struct Vertex{int neighborNum;//邻居节点个数Edge * headEdge;Vertex():neighborNum(0),headEdge(NULL){}};//图class Graph{public:int vertexNum;//总节点个数Vertex * V;//节点Graph():vertexNum(0),V(NULL){}Graph(int n){if (n <= 0){vertexNum = 0;V = NULL;}else{vertexNum = n;V = new Vertex[vertexNum];}}Graph(const Graph &g)//复制构造函数{vertexNum = g.vertexNum;if (vertexNum > 0){V = new Vertex[vertexNum];for (int i = 0; i < vertexNum; i++){V[i].neighborNum = g.V[i].neighborNum;Edge *pEg = g.V[i].headEdge;if (pEg != NULL)  {  V[i].headEdge = new Edge(pEg->startVertex,pEg->endVertex,pEg->weightEdge);  pEg = pEg->nextEdge;  }  Edge *pE = V[i].headEdge;  while (pEg != NULL)  {  pE->nextEdge = new Edge(pEg->startVertex,pEg->endVertex,pEg->weightEdge);  pE = pE->nextEdge;  pEg = pEg->nextEdge;  }}}elseV = NULL;}~Graph(){if (V != NULL){for (int i = 0; i < vertexNum; i++){Edge * pE = V[i].headEdge;V[i].headEdge = NULL;while (pE != NULL){Edge * pDel = pE;pE = pE->nextEdge;delete pDel;}}delete [] V;V = NULL;}}void addSingleEdge(int s, int e, int w);void showGraph();};

图类源文件

//graph.cpp#include <iostream>#include "graph.h"//添加单向边void Graph::addSingleEdge(int s, int e, int w){if (s == e || s >= vertexNum || e >= vertexNum || s < 0 || e < 0)return;//舍弃边界外的边,舍弃自环的边Edge * pE = new Edge(s,e,w);if (V[s].headEdge == NULL || V[s].headEdge->endVertex >= e)//从小到大排序{pE->nextEdge = V[s].headEdge;V[s].headEdge = pE;} else{Edge * pH = V[s].headEdge;while (pH->nextEdge != NULL && pH->nextEdge->endVertex < e)//从小到大排序pH = pH->nextEdge;pE->nextEdge = pH->nextEdge;pH->nextEdge = pE;}V[s].neighborNum++;return;}//显示图void Graph::showGraph(){using namespace std;if (vertexNum > 0){for (int i = 0; i < vertexNum; i++){cout << i << " :";if (V[i].headEdge != NULL){Edge * pH = V[i].headEdge;while (pH != NULL){cout << "   -> " << pH->endVertex << " (" << pH->weightEdge << ")";pH = pH->nextEdge;}}cout << endl;}}elsecout << "This Graph is empty!" << endl;return;}

调用主函数

//2_4_Graph//无向图#include <iostream>#include "graph.h"int main(){using namespace std;int nums,rows,s,e,w;cin >> nums >> rows;//输入图的节点总数,输入边的总行数Graph G0(nums);//构造一个 nums 个节点的图for (int i = 0; i < rows; i++){cin >> s >> e >> w;//输入边的 始节点,终节点,边权重G0.addSingleEdge(s,e,w);//无向图,添加单向边G0.addSingleEdge(e,s,w);//无向图,添加单向边}Graph G1 = G0;//调用复制构造函数G1.showGraph();//显示图return 0;}







0 0
原创粉丝点击