Search code examples
cgraphadjacency-listtraceroute

adjacency list graph implementation in c (any libraries)


I am working on a project where I make traceroutes to a certain IP address from 10-15 different IP addresses. Most of the traceroutes go along certain common routers on the way(hop) to the same destination. The resulting data gives me a graph. I think to represent this data the best way is an adjacency list. Is there any C library where I can get an instance of such a graph and add edges(hops) to it as I make different traceroute calls?


Solution

  • #include <stdio.h>
    #include <stdlib.h>
    
    // adjacency list implementation of graph using linked list in c
    
    struct adj_node {
        int index;
        struct adj_node * next;
    };
    
    void makeadj(struct adj_node *nod,int adj) {
        struct adj_node *newadj=(struct adj_node *)malloc(sizeof(struct adj_node));
        newadj->index=adj;
        newadj->next=NULL;
        while(nod->next!=NULL)nod=nod->next;
        nod->next=newadj;
    }
    
    int main(){
        int i;
        struct adj_node graph[4],*temp;
        for(i=0;i<4;i++){
            graph[i].index=i;graph[i].next=NULL;
        }
        //example
        makeadj(&graph[0],2);
        makeadj(&graph[0],3);
        makeadj(&graph[1],2);
        makeadj(&graph[2],0);
        makeadj(&graph[2],1);
        makeadj(&graph[2],3);
        temp=&graph[2];
        while(temp->next!=NULL){
            printf("%d",temp->next->index);
            temp=temp->next;
        }
        return 0;
    }