图---邻接表

#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;
}

猜你喜欢

转载自www.cnblogs.com/zhulmz/p/12076696.html