邻接表实现无向图(C++)

很早以前写的代码了,贴出来做个备份吧。用向量来存储一条邻接链表,存储可连通值。实现了判断是否连通,添加边,添加顶点的功能。

UnDirectGraph.h

#pragma once

#include “stdafx.h” #include <vector> using namespace std; class UnDirectGraph { private: int vCount; vector<int> *adj; public: int GetVCount(); UnDirectGraph(int vCount); void AddEdge(int v,int w); vector<int> &Vadj(int v); bool IsConnected(int v,int w); };

UnDirectGraph.cpp
#pragma once

#include “stdafx.h” #include “UnDirectGraph.h” using namespace std; UnDirectGraph::UnDirectGraph(int _vCount) { this->vCount=_vCount; adj=new vector<int>[vCount];

for (int i=0;i&lt;vCount;i++)
{
        adj[i].clear();
}

} void UnDirectGraph::AddEdge(int v,int w) { adj[v].push_back(w); adj[w].push_back(v); }

vector<int>& UnDirectGraph::Vadj(int v) { return adj[v]; }

bool UnDirectGraph::IsConnected(int v,int w) { for (vector<int>::iterator iter=adj[v].begin();iter!=adj[v].end();iter++) { if (*iter==w) { return true; } } return false; }

int UnDirectGraph::GetVCount() { return vCount; }

代码还算清晰,就不解释了,有问题留言反馈。谢谢。

comments powered by Disqus