首页 > 其他 > 详细

图---邻接表

时间:2019-12-21 14:26:32      阅读:78      评论:0      收藏:0      [点我收藏+]
#include<iostream>
#include<string>
#include<stdlib.h>
#define MAX_VERTEX_NUM 20 //最大顶点数
using namespace std;

typedef char VertexType;   //顶点数据类型
 //表结点
typedef struct ArcNode{
    int adjvex;           //该弧所指的顶点位置
    struct ArcNode *nextarc; //指向下一条弧
    string info;          //该弧相关信息
}ArcNode;
//顶点
typedef struct VNode{
    VertexType data;
    ArcNode *firstarc;
}VNode,AdjList[MAX_VERTEX_NUM];

//邻接表
typedef struct {
    AdjList vertices;
    int vexnum, arcnum;
    int kind;
}ALGraph;

//定位
int locateVex(ALGraph *g, char v)
{
    for(int i = 0; i < g->vexnum; i++){
        if(g->vertices[i].data == v){
            return i;
        }
    }
    return 0;
}

//创建
void CreateGraph(ALGraph *g)
{
    ArcNode *l;
    cout << "请输入顶点数与边数" << endl;
    cin >> g->vexnum >> g->arcnum;
    
    cout << "请输入顶点值" << endl;
    for(int i = 0; i < g->vexnum; i++){
        cin >> g->vertices[i].data;
    }
    char a , b;
    for(int i = 0; i < g->arcnum; i++){
        cout << "请输入第" << i + 1 << "条弧"<< endl;
        cin >> a >> b;
        l = new ArcNode;
        int r1 = locateVex(g, a);
        int r2 = locateVex(g, b);
        l->adjvex = r2;
        l->nextarc = g->vertices[r1].firstarc;
        g->vertices[r1].firstarc = l;
    }
}

//打印
void print(ALGraph *g)
{
    cout << "该图的邻接表为:" << endl;
    for(int i = 0; i < g->vexnum; i++){
        cout << i << " " << g->vertices[i].data;
        ArcNode *p = g->vertices[i].firstarc;
        while(p){
            cout << "->" << p->adjvex;
            p = p->nextarc;
        }
        cout << endl;
    }
}

int main()
{
    ALGraph G;
    CreateGraph(&G);
    print(&G);
    return 0;
}

技术分享图片

图---邻接表

原文:https://www.cnblogs.com/zhulmz/p/12076696.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!