Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
194 views
in Technique[技术] by (71.8m points)

Count outgoing links in adjacency list graph representation in C

I have a graph with adjacency list representation and want to find how many outgoing links each vertices has. I created a function to count nodes of linked list at a specific vertex, however, after calling count function, all nodes (edges) of this vertex are being removed from the graph (at least I'm not able to display them). How can I fix this?

Graph output of vertices and edges without calling count function:

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 -> 

After counting number of edges for vertex 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 ->

Graph structure:

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

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

Code for counting:

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
", c); 
    ...
} 
question from:https://stackoverflow.com/questions/65857400/count-outgoing-links-in-adjacency-list-graph-representation-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

all nodes (edges) of this vertex are being removed from the graph (at least I'm not able to display them)

That's because you are updating and setting the pointer to NULL at the very end:

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

try

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...