This post will cover graph data structure implementation in C using an adjacency list. The post will cover both weighted and unweighted implementation of directed and undirected graphs.

In the graph’s adjacency list representation, each vertex in the graph is associated with the collection of its neighboring vertices or edges, i.e., every vertex stores a list of adjacent vertices.

Directed Graph

For example, for the above graph, below is its adjacency list pictorial representation:

 
Adjacency List

1. Directed Graph Implementation

Following is the C implementation of a directed graph using an adjacency list:

Download  Run Code

Output:

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

 

As evident from the above code, in a directed graph, we only create an edge from src to dest in the adjacency list. Now, if the graph is undirected, we also need to create an edge from dest to src in the adjacency list, as shown below:

Download  Run Code

Output:

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

2. Weighted Directed Graph Implementation

In a weighted graph, each edge will have weight (or cost) associated with it, as shown below:

Weighted Directed Graph

Following is the implementation of a weighted directed graph in C using the adjacency list. The implementation is similar to that of an unweighted directed graph, except we are also storing weight info along with every edge.

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)

 
For weighted undirected graphs (as seen before for unweighted undirected graphs), create a path from dest to src as well in the adjacency list. The complete implementation can be seen here.

 
Also see:

Graph Implementation in C++ (without using STL)

Graph Implementation in C++ using STL

Graph Implementation in Java using Collections

Graph Implementation in Python