简体   繁体   中英

What is the difference between implementing an undirected graph with LinkedList vs HashMap? What is better for traversing BFS/DFS?

I've come across two implementations for an undirected graph (adjacency list), but I can't tell why would one be used over the other.

I successfully implemented DFS/BFS with a LinkedList, but cannot get the DFS to work with the HashMaps.

With the HashMaps, I know that the order of insertion is not maintained so does that mean you cannot do any traversing like DFS? If so, doesn't that defeat the purpose of using a HashTable because then how would you traverse properly without having the insertion order?

How can I check if a node is visited in a HashMap? Currently, I've created a new class Node that has a visited attribute. With the LinkedList implementation, I didn't need a new class so I directly used a variable of type <T> . Does having to make a new class affect the overall efficiency of using graphs?

HashMap is a subinterface of Collection , and every collection provides the method iterator() which will allow you to traverse the collection and visit every element in it.

An adjacency list is in theory a Set , and not a List , since the collection should not contain more than one copy of each edge. It also means that the order is not important.

HashMap uses a HashSet for its keyset, which is ideal. You can then use an object representing a pair for each key, for example, a Pair<String, String> , or you could just use a String formatted as "A,B" where A and B are the names of your vertices.

If you can use the provided classes, it is better to do that than to make your own. The libraries provided in JRE are written by professionals. You are not likely to improve upon their performance.

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