Representation of Graph using adjacency list in C

    This is the next type of graph representation. In the previous post, the adjacency matrix is used to represent the graph.

You can visit the below link to access the adjacency matrix.

https://rajeeva84.blogspot.com/2026/05/representation-of-graph-using-adjacency.html

It makes use of linked list. It uses vertexes. It 

#include <stdio.h>

#include <stdlib.h>

 struct g_Node {

    int g_vertex;

    struct g_Node* g_next;

};

struct Graph {

    int num_Vertices;

    struct g_Node** adjLists;

};

// let us Create a node

struct g_Node* createNode(int v) {

    struct g_Node* newNode = malloc(sizeof(struct g_Node));

    newNode->g_vertex = v;

    newNode->g_next = NULL;

    return newNode;

}

// here, is the graph code

struct Graph* createGraph(int vertices) {

    struct Graph* graph = malloc(sizeof(struct Graph));

    graph->num_Vertices = vertices;

    graph->adjLists = malloc(vertices * sizeof(struct g_Node*));

    for (int i = 0; i < vertices; i++)

        graph->adjLists[i] = NULL;

    return graph;

}

// Add the edges to the graph

void add_Edge(struct Graph* graph, int src, int dest) {

    // Add the edge directly from src -> dest

    struct g_Node* newNode = createNode(dest);

    newNode->g_next = graph->adjLists[src];

    graph->adjLists[src] = newNode;

    // It is for undirected graph: add dest -> src

    newNode = createNode(src);

    newNode->g_next = graph->adjLists[dest];

    graph->adjLists[dest] = newNode;

}

// Represent the graph

void print_Graph(struct Graph* graph) {

    for (int v = 0; v < graph->num_Vertices; v++) {

        struct g_Node* temp = graph->adjLists[v];

        printf("\nVertex %d: ", v);

        while (temp) {

            printf("%d -> ", temp->g_vertex);

            temp = temp->g_next;

        }

        printf("NULL");

    }

}

int main() {

    struct Graph* graph = createGraph(4);

    add_Edge(graph, 0, 1);

    add_Edge(graph, 0, 3);

    add_Edge(graph, 1, 2);

    add_Edge(graph, 2, 3);

    printf("Adjacency List:\n");

    print_Graph(graph);

    return 0;

}

Output:

Adjacency List:

Vertex 0: 3 -> 1 -> NULL

Vertex 1: 2 -> 0 -> NULL

Vertex 2: 3 -> 1 -> NULL

Vertex 3: 2 -> 0 -> NULL

That’s all. Thus the representation is implemented successfully.

If your graph deals with few edges compared to vertices(sparse), adjacency list is efficient.

Keep Coding!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Employee record management in C

Callables in Multithreading