【问题标题】:Count outgoing links in adjacency list graph representation in C在 C 中计算邻接列表图表示中的传出链接
【发布时间】:2021-01-23 08:59:51
【问题描述】:

我有一个带有邻接表表示的图,并且想找出每个顶点有多少传出链接。我创建了一个函数来计算特定顶点处的链表节点,但是,在调用 count 函数之后,该顶点的所有节点(边)都将从图中删除(至少我无法显示它们)。我该如何解决这个问题?

不调用count函数的顶点和边的图形输出:

Vertex 0: 3 -> 2 -> 1 -> 
Vertex 1: 4 -> 
Vertex 2: 6 -> 1 -> 5 -> 4 -> 
Vertex 3: 4 -> 5 -> 6 -> 0 -> 
Vertex 4: 6 -> 2 -> 1 -> 
Vertex 5: 0 -> 3 -> 2 -> 6 -> 4 -> 1 -> 
Vertex 6: 0 -> 3 -> 5 -> 2 -> 4 -> 1 -> 

计算顶点 4 的边数后:

Outgoing links: 3

Vertex 0: 3 -> 2 -> 1 -> 
Vertex 1: 4 -> 
Vertex 2: 6 -> 1 -> 5 -> 4 -> 
Vertex 3: 4 -> 5 -> 6 -> 0 -> 
Vertex 4: 
Vertex 5: 0 -> 3 -> 2 -> 6 -> 4 -> 1 -> 
Vertex 6: 0 -> 3 -> 5 -> 2 -> 4 -> 1 ->

图形结构:

typedef struct graph {
    int numberV;
    int numberE;
    struct vertex **adjList;
} GraphT; 

typedef struct vertex {
    int vertex;
    struct vertex *next; 
} VertexT; 

计数代码:

int countLinks(GraphT *graph, int vertex) {
    int count = 0;
    GraphT *current = graph;
    while (current->adjList[vertex] != NULL) {
        count++;
        current->adjList[vertex] = current->adjList[vertex]->next;
    }
    return count; 
}

int main () {
    ...
    int c = countLinks(graph, 4); 
    printf("Outgoing links: %d\n", c); 
    ...
} 

【问题讨论】:

    标签: c


    【解决方案1】:

    这个顶点的所有节点(边)都被从图中删除(在 至少我无法显示它们)

    那是因为您在最后更新并设置指向NULL 的指针:

    int countLinks(GraphT *graph, int vertex) {
        int count = 0;
        GraphT *current = graph;
        while (current->adjList[vertex] != NULL) {
            count++;
            current->adjList[vertex] = current->adjList[vertex]->next; //here
        }
        return count; 
    }
    

    试试

    int countLinks(GraphT *graph, int vertex) {
        int count = 0;
        GraphT *current = graph;
        struct vertex *temp;
    
        temp = current->adjList[vertex];
        while (temp != NULL) {
            count++;
            temp = temp->next;
        }
        return count; 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-04
      相关资源
      最近更新 更多