Given an undirected or a directed graph, implement the graph data structure without using any container provided by any programming language library (e.g., STL in C++ or Collections in Java, etc.). Implement for both weighted and unweighted graphs using the adjacency list representation.

Prerequisite:

Terminology and Representations of Graphs

 
As we already know, the adjacency list associates each vertex in the graph with the collection of its neighboring vertices or edges, i.e., every vertex stores a list of adjacent vertices. There are many variations of adjacency list representation depending upon the implementation.

Directed Graph

For example, below is the adjacency list representation of the above graph:

Adjacency List

The adjacency list representation of graphs also allows additional data storage on the vertices but is practically very efficient when it contains only a few edges.

1. Directed Graph implementation in C++

Download  Run Code

Output:

0 —> 1
1 —> 2
2 —> 1 —> 0
3 —> 2
4 —> 5
5 —> 4

2. Weighted Directed Graph implementation in C++

We know that in a weighted graph, every edge will have a weight or cost associated with it, as shown below:

Weighted Directed Graph

Following is the C++ implementation of a directed weighted graph. The implementation is similar to the above implementation of unweighted graphs, except we will also store every edge’s weight in the adjacency list.

Download  Run Code

Output:

(0, 1, 6)
(1, 2, 7)
(2, 1, 4)    (2, 0, 5)
(3, 2, 10)
(4, 5, 1)
(5, 4, 3)

 
See more:

Graph Implementation in C++ using STL

Implement Graph Data Structure in C

Graph Implementation in Java using Collections

Graph Implementation in Python