Adjacency List in C for undirected (unweighted) graph

348 views Asked by At

Here is my code:

#define V 5

typedef struct edge* link;

//structure for reprenting edges
typedef struct edge{
    int dst;        //number of destination node
    //int weight;   //for weigthed graphs
    link next;      //link to next edge
} edge_t;

link new_edge(int dst, link next) {
    link edge = (link) malloc(sizeof(edge_t));

    edge->dst = dst;
    edge->next = next;
    return edge;
}

int main() {

    link edge;
    link adj[V];
    //the array contains V pointers to lists of edges
    //each list for each node of my graph

    int i;
    int j;

    //all lists are empty at beginning
    for (i = 0; i < V; i ++) {
        adj[i] = NULL;
    }

    printf("input the edges:\n");
    
    while (scanf("%d %d", &i, &j) == 2) {
        adj[i] = new_edge(j, adj[i]);
        //in the list for node i
        //put the edge to node j
        adj[j] = new_edge(i, adj[j]); //if it is undirect
        //in the list for node j
        //put the edge to node i
    }
    
    printf("adjacency list is: \n");
    //cycle over the nodes
    for (i=0; i<V; i++) {
        if (adj[i] == NULL) {
            printf("%d is null list\n", i);
        }
        //print all the edges for that node
        for (edge = adj[i]; edge != NULL; edge = edge -> next) {
            printf("edge %d -> %d\n", i, edge->dst);
        }
    }
}

INPUT:
0 1
0 2
1 3
stop
OUTPUT:
adjacency list is:
edge 0 -> 2
edge 0 -> 1
edge 1 -> 3
edge 1 -> 0
edge 2 -> 0
edge 3 -> 1
4 is null list

This image shows how my new_edge function works, blue area(in pic) is changing so I can traverse through the list, so my question is why blue area is equal to NULL?, cause it is pointing to last item in the list, I thought it won't be NULL(P.S I verified it is null when I traversed through the list in order to print it).

enter image description here

1

There are 1 answers

0
MikeCAT On BEST ANSWER

The elements of adj are pointers to nodes, not nodes. On the other hand, what next in the nodes point at are nodes, not pointers to nodes. Therefore, next will not point at the elements of adj.

This is how your code actually work:

how your code actually work

As you see, the pointers are not looping back and your blue area (elements of adj that have nodes added) is not equal to NULL.