图邻接列表实现(C)

时间:2018-05-21 10:11:13

标签: c graph adjacency-list

我正在尝试使用以下定义在C中创建图形的相邻ist表示...

typedef struct edge
{
    int to_vertex;
    int weight;
} Edge;

typedef struct edgeNode
{
    Edge edge;
    struct edgeNode *next;
} *EdgeNodePtr;

typedef struct edgeList
{
    EdgeNodePtr head;
} EdgeList;

typedef struct graph
{
    int V;
    EdgeList *edges;
} Graph;

为图表创建和添加所有值的主要功能是

    int numEdges;
    int edgeToVertex;
    int weight;
    EdgeNodePtr new_node;
    Graph G;

    EdgeNodePtr current;
    int *inDeg;


    scanf("%d", &G.V);
    G.edges = malloc(G.V * sizeof(EdgeList));

    for (int i = 0; i < G.V; i++)
    {
        scanf("%d", &numEdges);
        G.edges[i].head = NULL;


        for (int j = 0; j < numEdges; j++)
        {
            new_node = malloc(sizeof(*new_node));

            scanf("%d,%d", &edgeToVertex, &weight);
            new_node->edge.to_vertex = edgeToVertex;
            new_node->edge.weight = weight;

            new_node->next = G.edges[i].head;
            new_node = G.edges[i].head;

        }
    }

出于某种原因,我似乎无法弄清楚图形不会创建,我尝试触发它,它会添加一个节点,但节点将始终相同。任何帮助表示赞赏

1 个答案:

答案 0 :(得分:0)

这看起来很奇怪:

        new_node->next = G.edges[i].head;
        new_node = G.edges[i].head;
当您使用new_node覆盖head

也许你想这样做:

        new_node->next = G.edges[i].head;
        G.edges[i].head = new_node;

使head指向新节点。