Hi I’m going about implementing a Graph data structure for a course (the graph isn’t part of the requirement, I’ve chosen to use it to approach the problem) and my first thought was to implement it using an adjacency list, because that requires less memory, and I don’t expect to have that many edges in my graph.
But then it occurred to me. I can implement an adjacency list Graph data structure using a Map (HashMap to be specific). Instead of the list of vertices I’ll have a Map of vertices, which then hold a short list of edges to vertices.
This seems to be the way to go for me. But I was wondering if anyone can see any drawbacks that a student such as I might have missed in using a HashMap for this? (unfortunately I recall being very tired whilst we were going over HashMaps…so my knowledge of them is less than all the other data structures I know of.) So I want to be sure.
By the way I’m using Java.
The two primary ways of representing a graph are:
Since you will not have too many edges (i.e. the adjacency matrix representing your graph would be sparse), I think your decision to use the list instead of the matrix is a good one since, as you said, it will indeed take up less space since no space is wasted to represent the absent edges. Furthermore, the
Mapapproach seems to be logical, as you can map eachNodeof your graph to the list ofNodes to which it is connected. Another alternative would be to have eachNodeobject contain, as a data field, the list of nodes to which it is connected. I think either of these approaches could work well. I’ve summed it up below.First approach (maintain the map):
Second approach (data built into
Nodeclass):