C++邻接表实现无向图、有向图

本文详细介绍了如何使用C++编程语言,通过邻接表结构来实现无向图和有向图的数据结构。内容涵盖邻接表的基本概念,以及在C++中创建、插入边、遍历图的相关操作,帮助读者深入理解图的抽象数据类型及其在实际问题中的应用。
摘要由CSDN通过智能技术生成
/*********************邻接表实现有向图******************/
//邻接表实现有向图缺点:只有出度,没有入度;解决方法:逆邻接表、十字链表
//边节点类
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;
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值