利用邻接表创建无向图

#include<iostream>
using namespace std;
#define MVNum 100
#define OK 1
typedef char VerTexType; // 顶点信息
typedef int OtherInfo; // 和边相关的信息
typedef struct ArcNode {  // 边结点
    int adjvex;  // 该边所指向的顶点的位置
    struct ArcNode* nextarc; // 指向下一条边的指针
    OtherInfo info; 
}ArcNode;
typedef struct VNode {
    VerTexType data; 
    ArcNode* firststarc; // 指向第一条边依附顶点的边的指针
}VNode, AdjList[MVNum];  // AdjList表示邻接表类型
typedef struct {
    AdjList vertices; // 邻接表
    int vexnum, arcnum;
}ALGraph;
int LocateUDG(ALGraph G, VerTexType v)
{
    for (int i = 0; i < G.vexnum; i++)
    {
        if (G.vertices[i].data == v)
        {
            return i;
        }
    }
    return -1;
}
int CreateUDG(ALGraph& G)
{
    cout << "请输入总顶点数,总边数:";
    cin >> G.vexnum >> G.arcnum;
    cout << endl;
    cout << "输入点的名称: " << endl;
    for (int i = 0; i < G.vexnum; i++)
    {
        cout << "请输入第" << i + 1 << "个点的名称:";
        cin >> G.vertices[i].data;
        G.vertices[i].firststarc = NULL;
    }
    cout << endl;
    cout << "请输入一条边依附的顶点:" << endl;
    for (int k = 0; k < G.arcnum; k++)
    {
        VerTexType v1, v2;
        cout << "请输入第" << k + 1 << "条依附的两个顶点:";
        cin >> v1 >> v2;
        int i = LocateUDG(G, v1);
        int j = LocateUDG(G, v2);
        ArcNode* p1 = new ArcNode;
        p1->adjvex = j;
        p1->nextarc = G.vertices[i].firststarc;
        G.vertices[i].firststarc = p1;
        ArcNode* p2 = new ArcNode;
        p2->adjvex = i;
        p2->nextarc = G.vertices[i].firststarc;
        G.vertices[j].firststarc = p2;
    }
    return OK;
}
int main()
{
    cout << "邻接表创建无向图" << endl;
    ALGraph G;
    CreateUDG(G);
    for (int i = 0; i < G.vexnum; i++)
    {
        VNode temp = G.vertices[i];
        ArcNode* p = temp.firststarc;
        if (!p)
        {
            cout << G.vertices[i].data << endl;
        }
        else
        {
            cout << temp.data;
            while (p)
            {
                cout << "->" << p->adjvex;
                p = p->nextarc;
            }
        }
        cout << endl;
    }
    return 0;
}

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

FG.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值