Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C
  • C Basics
  • C Data Types
  • C Operators
  • C Input and Output
  • C Control Flow
  • C Functions
  • C Arrays
  • C Strings
  • C Pointers
  • C Preprocessors
  • C File Handling
  • C Programs
  • C Cheatsheet
  • C Interview Questions
  • C MCQ
  • C++
Open In App
Next Article:
C program to implement DFS traversal using Adjacency Matrix in a given Graph
Next article icon

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:

  • Graph and it's representations
  • Graph and its representations
  • Print Adjacency List for a Directed Graph

Next Article
C program to implement DFS traversal using Adjacency Matrix in a given Graph

A

aakanksha21c
Improve
Article Tags :
  • C Programs
  • C Language
  • C-DSA

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
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences