Open In App

C Program to Implement Adjacency List

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

An adjacency list is a data structure used to represent a graph in the form of an array of linked lists. The index of the array represents a vertex and each element in its linked list represents the other vertices of the graph that form an edge with the vertex at the index. In this article, we will learn about the implementation of an adjacency list to represent a graph in C.

Implementation of Adjacency List in C

Representing a graph through the adjacency list saves a lot of space and is more efficient than the other methods that are used to represent a graph in C. To represent a graph using an adjacency list an array of linked lists is created where the index of the array represents the source vertex and all the other adjacent vertices to this node are stored in the form of a linked list in the array.

For example, if there are n vertices in the graph So, we will create an array of list of size n: adjList[n]. Here, adjList[0] will have all the nodes which are connected to vertex 0, called as neighbour vertex 0. Similarly, adjList[1] will have all the nodes which are connected to vertex 1 , and so on.

Representation of Undirected Graph Adjacency List

Let us consider the below undirected graph having 3 nodes labeled 0, 1, 2.

Graph-Representation-of-Undirected-graph-to-Adjacency-List
Undirected Graph to Adjacency List

First, create an array of lists of size 3 as there are 3 vertices in the graph. Here, we can see that node 0 is connected to both nodes 1 and 2 so, Vertex 0 has 1 and 2 as its neighbors so, inserting vertex 1 and 2 at index 0 of the array. Vertex 1 is having 0 and 2 as neighbors so, inserting vertex 0 and 2 at index 1 of the array. Similarly, Vertex 2 is having 0 as a neighbor so, inserting vertex 0 at index 2 of the array.

Representation of Directed Graph to Adjacency List

Let us consider the below directed graph having 3 nodes labeled 0, 1, 2.

Graph-Representation-of-Directed-graph-to-Adjacency-List
Directed Graph to Adjacency List

First, create an array of lists of size 3 as there are 3 vertices in the graph. Now, Vertex 0 has no neighbors so, leaving index 0 of the array empty. Vertex 1 is having 0 and 2 as neighbors so, inserting vertex 0 and 2 at index 1 of the array. Similarly, Vertex 2 is having 0 as a neighbor so, inserting vertex 0 at index 2 of the array.

Algorithm to Implement Adjacency List

To represent a graph using an adjacency list in C follow the below approach:

  • Create a struct Graph that will have the following data members:
    • numVertices: represent the total number of vertices in a graph.
    • adjlist: a double pointer to represent an array of lists.
    • isDirected: a flag variable to denote whether the graph is directed or not.
  • Create an array of linked lists adjlist of size equal to the number of vertices in the graph.
  • Initially point each array element to NULL until the graph is initialized.
  • Implement a function addEdge(src,dest) to add an edge for the graph.
    • Create a new node with data equal to dest and add it in the adjlist[src].
    • If the graph is undirected then create a new node with data to src and add it in the adjlist[dest].
  • Implement a function printGraph() to print the adjacency list for the graph.
    • Iterate through each vertex of the graph present in the adjacency list.
    • Print the vertex.
    • Initialize a temporary pointer temp at the head of the list present at adjlist[vertex].
    • While temp is not equal to NULL:
      • print temp->data.
      • Move temp to temp->next.

C Program to Implement Adjacency List

The following program demonstrates how we can implement an adjacency list for graphs in C.

C
// C Program to implement adjacency list in C++

#include <stdio.h>
#include <stdlib.h>

// Structure to represent a node in the adjacency list
struct Node {
    int vertex;
    struct Node* next;
};

// Structure to represent the graph
struct Graph {
    int numVertices;
    struct Node** adjLists;
    int isDirected;
};

// Function to create a new node
struct Node* createNode(int v) {
    struct Node* newNode = malloc(sizeof(struct Node));
    newNode->vertex = v;
    newNode->next = NULL;
    return newNode;
}

// Function to create a graph
struct Graph* createGraph(int vertices, int isDirected) {
    struct Graph* graph = malloc(sizeof(struct Graph));
    graph->numVertices = vertices;
    graph->isDirected = isDirected;

    // Create an array of adjacency lists
    graph->adjLists = malloc(vertices * sizeof(struct Node*));

    // Initialize each adjacency list as empty
    for (int i = 0; i < vertices; i++) {
        graph->adjLists[i] = NULL;
    }

    return graph;
}

// Function to add an edge to the graph
void addEdge(struct Graph* graph, int src, int dest) {
    // Add edge from src to dest
    struct Node* newNode = createNode(dest);
    newNode->next = graph->adjLists[src];
    graph->adjLists[src] = newNode;

    // If the graph is undirected, add an edge from dest to src as well
    if (!graph->isDirected) {
        newNode = createNode(src);
        newNode->next = graph->adjLists[dest];
        graph->adjLists[dest] = newNode;
    }
}

// Function to print the adjacency list representation of the graph
void printGraph(struct Graph* graph) {
    printf("Vertex:  Adjacency List\n");
    for (int v = 0; v < graph->numVertices; v++) {
        struct Node* temp = graph->adjLists[v];
        printf("%d --->", v);
        while (temp) {
            printf(" %d ->", temp->vertex);
            temp = temp->next;
        }
        printf(" NULL\n");  
    }
}

int main() {
    // Create an undirected graph with 3 vertices
    struct Graph* undirectedGraph = createGraph(3, 0);

    // Add edges to the undirected graph
    addEdge(undirectedGraph, 0, 1);
    addEdge(undirectedGraph, 0, 2);
    addEdge(undirectedGraph, 1, 2);

    printf("Adjacecncy List for Undirected Graph:\n");
    printGraph(undirectedGraph);

    // Create a directed graph with 3 vertices
    struct Graph* directedGraph = createGraph(3, 1);

    // Add edges to the directed graph
    addEdge(directedGraph, 1, 0);
    addEdge(directedGraph, 1, 2);
    addEdge(directedGraph, 2, 0);

    printf("\nAdjacecncy List for Directed Graph:\n");
    printGraph(directedGraph);

    return 0;
}


Output

Adjacecncy List for Undirected Graph:
Vertex: Adjacency List
0 ---> 2 -> 1 -> NULL
1 ---> 2 -> 0 -> NULL
2 ---> 1 -> 0 -> NULL

Adjacecncy List for Directed Graph:
Vertex: Adjacency List
0 ---> NULL
1 ---> 2 -> 0 -> NULL
2 ---> 0 -> NULL

Time Complexity: O(V+E), where V is the total number of vertices and E is the total number of edges.
Auxiliary Space: O(V+E)

Related Articles

You can go through the following articles to improve your understanding about graph data structure and it's representations:


Next Article
Article Tags :

Similar Reads