Graph Representation by Adjacency List
Adjacency List using Linked list
There are many ways to represent a graph. Two of the most famous ways are Adjacency matrix and Adjacency list. We can represent a Graph by creating the Adjacency list using an array linked lists for all the possible nodes.
We will take integers as nodes, so an array of linked lists will work. In the array, the linked list in ith index will denote the list of nodes that can be arrived directly from the node i.
Graph Representation by Adjacency List | PrepInsta

Explanation
Prerequisites : What is a Graph?
Let us say we have 6 nodes, and they are 0,1,2,3,4,5 respectively. And There are 7 edges, in between the following nodes : (1,2), (2,3), (1,0), (1,5), (5,2), (5,4), (0,3). So,
- from node 0, we can directly visit the nodes namely 1, 3.
- from node 1, we can directly visit the nodes namely 0, 2, 5.
- from node 2, we can directly visit the nodes namely 1, 3, 5.
- from node 3, we can directly visit the nodes namely 0, 2.
- from node 4, we can directly visit the node namely 5.
- from node 5, we can directly visit the nodes namely 1, 2, 4.
So if we now see the array of the linked list, it will be like, [(1, 3), (0, 2, 5), (1, 3, 5), (0, 2), (5), (1, 3, 4)].
Implementing by this way will help us using different algorithms to sove graph theory problems, like DFS, BFS, etc.
Use of STL in C++ for Graph Representation by Adjacency List
- We have to first declare the array of vector, by, vector Adj[v]
- Where v is the number of vertices, here say 6.
- Then we will create a function that will take two integers as argument and add those two nodes with each other, i.e, void AddNodes(int a, int b).
Here is the code that implements the graph previously mentioned
#include <bits/stdc++.h>
// Now we will take the output :
Output :
Want to traverse the graph? Here is how to DFS Traverse a graph