编辑代码

#include <stdio.h>
#include "windows.h"

#define MaxVertex 5     // 规定矩阵最大可存多少个结点

typedef char E;

// 存边节点
typedef struct Node{
    int edge;
    struct Node *next;
}* node;

// 存节点头节点
typedef struct Head{
    E element;
    struct Node * next;
}* head;

// 图
typedef struct matrixGraph {
    int vertexCount, edgeCount;     //存放 结点总数与边总数
    struct Head vertex[MaxVertex];
} *Graph;

// create一个新的图
Graph create() {
    Graph graph = malloc(sizeof(struct matrixGraph));
    graph->vertexCount = graph->edgeCount = 0;
    return graph;
}

// 添加结点
void addVertex(Graph graph, E element) {
    if (graph->vertexCount != MaxVertex) {
        graph->vertex[graph->vertexCount].element = element;
        graph->vertex[graph->vertexCount++].next = NULL;
    }
}

//添加边,往邻接表添加
void addEdge(Graph graph, int a, int b) {
    node tmp = graph->vertex[a].next;   //取结点下一个
    node E = malloc(sizeof (struct Node));  // 创建新的存边节点
    E->edge = b;
    E->next = NULL;
    // 如果结点下一个为NULL ,则直接添加在后面
    while (tmp){
        // 如果 边已经存在则直接返回,(可以释放内存E)不过我懒的写
        if (tmp->edge == b) return;
        // 如果下个为NULL , 则直接添加
        if (!tmp->next){
            tmp->next = E;
            graph->edgeCount++;
            return;
        }
        tmp = tmp->next;
    }
    // 直接添加
    graph->vertex[a].next = E;
    graph->edgeCount++;
}

// 打印邻接矩表
void f(Graph graph){
    for (int i = 0; i < graph->vertexCount; ++i) {
        printf("%d | %c",i,graph->vertex[i].element);
        node tmp = graph->vertex[i].next;
        while (tmp){
            printf("-> %d",tmp->edge);
            tmp = tmp->next;
        }
        printf("\n");
    }
}

int main(){
    Graph graph = create();

    addVertex(graph,'A');
    addVertex(graph,'B');
    addVertex(graph,'C');
    addVertex(graph,'D');

    addEdge(graph,0,1);
    addEdge(graph,1,2);
    addEdge(graph,2,3);
    addEdge(graph,3,0);
    addEdge(graph,2,0);

    f(graph);
}