简体   繁体   中英

Java - Nodes vs Ints for an graph implemented using Adjacency list

I'm studying for technical interviews and graphs are kind of hard for me. I'm easy with adjacency matrix but confused with implementation of adjacency lists.

Problem is that most of the implementations of adjacency lists, that I see online ( Example1 , Example2 and Example3 ) don't use nodes at all. They just use a HashMap of ints and LinkedLists. Is this even correct? Because the definition ( Wikipedia ) says that it consists of vertices or nodes. Moreover most implementations of graphs using Adjacency matrix use nodes as opposed to ints. Example4 . Am I missing something is this puzzle?

I understand that using ints as opposed to nodes is more space efficient, however it leads to many more complications. For Example, check out this piece of code from example1 -

// add edge from vertices v1 to v2
void addEdge(int v1,int v2){
adj.get(v1).add(v2);
}

its purpose is to add an edge from v1 to v2. It completely ignores the possibility that there may be more than one vertices with same int value, in which case it leaves open the possibility that the method addEdge() can add an edge between unintended vertices.

So are implementations of Adjacency lists in Example1,2,3 wrong? If they are right, will it be bad if I implement an adjacency list using nodes instead of ints? I don't want my interviewers to think I'm some idiot lol

You can use Node(that contains the datatype) or use the datatype (in your examples Integer) straight away and they will both work

Using Node however is a better choice for several reasons

  1. Avoid the problems you rightly mentioned with duplicate data values
  2. Using a Node is more object oriented. It allows the Graph class to work with any datatype that the Node holds. This makes the code more portable since the graph can work with String, Long, Integer etc
  3. To take advantage of the portability I mentioned above, a Node class should be defined like this

     class Node<T>{ T data; } 

Therefore you should always use a Node (containing the datatype) in interviews as it looks better and shows you care about designing proper code.

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM