/*********************邻接表实现有向图******************/
//邻接表实现有向图缺点:只有出度,没有入度;解决方法:逆邻接表、十字链表
//边节点类
template<class Type>
class EdgeNode
{
public:
int adjvex;//邻节点域,存储该节点对应的下标
//int weight;//用于存储权值,非网图不需要
EdgeNode *next;//链域,指向下一个邻节点
//EdgeNode(){}
EdgeNode(int adj, EdgeNode *n = nullptr) :adjvex(adj), next(n){}
};
//顶点表节点类
template<class Type>
class VertexNode
{
public:
Type data;//顶点表域,存储顶点信息
EdgeNode<Type> *firstedge;//边表头指针
VertexNode(){}
VertexNode(Type d, EdgeNode<Type> *fir = nullptr) :data(d), firstedge(fir){}
};
//无向图类
template<class Type>
class UndirectedGraph
{
private:
VertexNode<Type> AdjList[MAX];//顶点数组
int numVertexes, numEdges;//图中当前顶点数和边数
Type readType();//外界读取一个Type型数据
int getPosition(Type el);//获取el在邻接表表头节点的位置
public:
UndirectedGraph();//创建图(自己输入)
~UndirectedGraph();//析构函数
void print();//打印邻接表
};
//获取el在邻接表表头节点的位置
template<class Type>
int UndirectedGraph<Type>::getPosition(Type el)
{
for (int i = 0; i < this->numVertexes; i++)
{
if (this->AdjList[i].data == el)
return i;
}
return -1;
}
//外界读取一个Type型数据
template<class Type>
Type UndirectedGraph<Type>::readType()
{
cout << "input a data: ";
Type el;
cin >> el;
return el;
}
//创建图
template<class Type>
UndirectedGraph<Type>::UndirectedGraph()
{
Type c1, c2;
C++邻接表实现无向图、有向图
最新推荐文章于 2024-07-10 11:47:17 发布
本文详细介绍了如何使用C++编程语言,通过邻接表结构来实现无向图和有向图的数据结构。内容涵盖邻接表的基本概念,以及在C++中创建、插入边、遍历图的相关操作,帮助读者深入理解图的抽象数据类型及其在实际问题中的应用。
摘要由CSDN通过智能技术生成