C Program to Implement Adjacency List
Last Updated : 03 Jul, 2024
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.
Undirected Graph to Adjacency ListFirst, 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.
Directed Graph to Adjacency ListFirst, 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:
Similar Reads
C program to implement Adjacency Matrix of a given Graph
Given a undirected Graph of N vertices 1 to N and M edges in form of 2D array arr[][] whose every row consists of two numbers X and Y which denotes that there is a edge between X and Y, the task is to write C program to create Adjacency Matrix of the given Graph. Examples: Input: N = 5, M = 4, arr[]
3 min read
C program to implement DFS traversal using Adjacency Matrix in a given Graph
Given a undirected graph with V vertices and E edges. The task is to perform DFS traversal of the graph. Examples: Input: V = 7, E = 7Connections: 0-1, 0-2, 1-3, 1-4, 1-5, 1-6, 6-2See the diagram for connections: Output : 0 1 3 4 5 6 2Explanation: The traversal starts from 0 and follows the followin
3 min read
Linked List C/C++ Programs
The Linked Lists are linear data structures where the data is not stored at contiguous memory locations so we can only access the elements of the linked list in a sequential manner. Linked Lists are used to overcome the shortcoming of arrays in operations such as deletion, insertion, etc. In this ar
2 min read
C Program To Delete Alternate Nodes Of A Linked List
Given a Singly Linked List, starting from the second node delete all alternate nodes of it. For example, if the given linked list is 1->2->3->4->5 then your function should convert it to 1->3->5, and if the given linked list is 1->2->3->4 then convert it to 1->3. Recomm
3 min read
C Program To Check If Two Linked Lists Are Identical
Two Linked Lists are identical when they have the same data and the arrangement of data is also the same. For example, Linked lists a (1->2->3) and b(1->2->3) are identical. . Write a function to check if the given two linked lists are identical. Recommended: Please solve it on "PRACTICE
3 min read
C Program to Detect Cycle in a Directed Graph
Given a directed graph, check whether the graph contains a cycle or not. Your function should return true if the given graph contains at least one cycle, else return false. For example, the following graph contains three cycles 0->2->0, 0->1->2->0 and 3->3, so your function must return true. Recomme
3 min read
C Program For Writing A Function To Delete A Linked List
Algorithm For C:Iterate through the linked list and delete all the nodes one by one. The main point here is not to access the next of the current pointer if the current pointer is deleted. Implementation: C/C++ Code // C program to delete a linked list #include<stdio.h> #include<stdlib.h
2 min read
C Program For Finding Length Of A Linked List
Write a function to count the number of nodes in a given singly linked list. For example, the function should return 5 for linked list 1->3->1->2->1. Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Iterative Solution: 1) Initialize count as 0 2) Initia
2 min read
Kruskal's Algorithm (Simple Implementation for Adjacency Matrix)
Below are the steps for finding MST using Kruskal's algorithm Sort all the edges in non-decreasing order of their weight. Pick the smallest edge. Check if it forms a cycle with the spanning tree formed so far. If cycle is not formed, include this edge. Else, discard it. Repeat step#2 until there are
9 min read
C Program For Deleting A Node In A Doubly Linked List
Pre-requisite: Doubly Link List Set 1| Introduction and Insertion Write a function to delete a given node in a doubly-linked list. Original Doubly Linked List Recommended: Please solve it on "PRACTICE" first, before moving on to the solution. Approach: The deletion of a node in a doubly-linked list
4 min read