邻接列表:
#pragma once
#include <list>
#include <vector>
#include <algorithm>
#include "Graph.h"
using std::vector;
using std::list;
using std::find;
template <typename T>
class graphList
{
private:
vector<list<T>> g; //邻接列表
vector<T> v; //顶点集合
eMode mode;
int _get(const T& vex) {
for (int i = 0; i < v.size(); i++)
{
if (vex == v[i])
{
return i;
}
}
return -1;
}
public:
graphList(eMode mode= undirected):mode(mode)
{
}
bool insert(const T& ver)
{
if (_get(ver) != -1)
{
return false;
}
v.push_back(ver);
g.push_back(list<T>({
ver }));
return true;
}
bool remove(const T& ver)
{
int i = _get(ver);
if (i != -1)
{
return false;
}
v.erase(v.begin() + i);
g.erase(g.begin() + i);
return true;
}
bool link(const T& t1, const T& t2)
{
int v1 = _get(t1);
int v2 = _get(t2);
//顶点不能自己和自己连接
if (v1 == v2 || v1 == -1 || v2 == -1)
{
return false;
}
switch(mode)
{
case directed:
g[v1].push_back(v[v2]);
break;
case undirected:
g[v1].push_back(v[v2]);
g

本文介绍了使用C++编程语言如何实现图数据结构,包括通过邻接矩阵和邻接列表两种方式。在邻接矩阵中,博主详细阐述了二维数组的使用来表示图的连接关系。而在邻接列表部分,讨论了如何用链表来存储图的邻接节点。在主函数中,展示了如何实例化并操作这些数据结构。
最低0.47元/天 解锁文章
571

被折叠的 条评论
为什么被折叠?



