Adjacency List - Theory and Implementation in Java/C++ With Examples

In this article, we’re talking about an adjacency list. A graph is a collection of edges and vertices. It is a convenient way of representing a network of nodes.

There are multiple ways to represent a graph while programming. One of the popular representations is adjacency list.

Under the adjacency list representation, a graph is represented as an array of lists. The array length is equal to the number of vertices. Each block of the array represents a vertex of the graph. Each block contains the list of other vertices that particular vertex is connected to.

The Idea Behind an Adjacency List

Let’s look at an example to understand it better. Let the graph be as follows:

graph

This is an undirected graph, which means that an edge represents a two way connection.

We can use adjacency list for both, directed as well as undirected graphs. Look at the comments in the code to see the difference.

The adjacency list for the above graph will look like:

graph

The left side shows the array and the right side shows the list of vertices stored in the array.

Implementation of an Adjacency List

To implement an adjacency list we use dynamic arrays. Dynamic arrays are easy to expand. Our adjacency list is going to be an array list of the array list. Let’s go over the code.

To add an edge to the adjacency list we have the following code :

We have two statements in the function since we are considering an undirected graph. Had the graph been directed, the edge from u to v will be added as:

The following piece of code prints the adjacency list:

Adjacency List Implementation in Java

Adjacency List Implementation in C++

Output

The output of the code above is:

Conclusion

This tutorial covered adjacency list and its implementation in Java/C++. To learn more about graphs, refer to this article on basics of graph theory.

By admin

Leave a Reply

%d bloggers like this: