gpt4 book ai didi

java - 使用 HashMap 实现图

转载 作者:行者123 更新时间:2023-11-30 08:06:04 27 4
gpt4 key购买 nike

我是 Java 的新手,所以在触发快乐的否决投票之前请记住这一点。我熟悉使用数组的整数图的流行实现。

Graph{
int vertices;
LinkedList<Integer>[] adj;

Graph(int vertices){
this.vertices = vertices;
adj = new LinkedList<>();
for(int i= 0; i <vertices; i++){
adj[i] = new LinkedList();
}
}

然而,这种实现最适合整数图。如果我想要角色的实现图,这个实现不会直接使自己可用。所以我尝试使用 HashMap 来实现。

public class Graph {
int vertices;
HashMap<Character, LinkedList<Character>> adj;


Graph(int item){

this.vertices = item;
adj = new HashMap<>();

}
}

我在 Java 语法上有点卡住的地方是向这个 HashTable 添加键和值。我要做的是实现这个方法。

public void add(Character a, Character b){

if (adj.containsKey(a)){

//get a reference to the existing linked list
//add to the existing LinkedList
}else{

//create a new LinkedList and add to it.
}

}
}

我可以在不完整的 add 方法上使用一些帮助,以及如何在构建图形后遍历 this adj HashMap。

最佳答案

因为你的问题只是关于语法,你可以这样做:

public void add(Character a, Character b){

if (adj.containsKey(a)){

//get a reference to the existing linked list
LinkedList<Character> l = adj.get(a);

//add to the existing LinkedList
//You need to do a null check here to make sure (l != null)
l.add(b)
}else{

//create a new LinkedList and add to it.
LinkedList<Character> l = new LinkedList<Character>();
l.add(b);
adj.put(a, l);
}

}
}

关于java - 使用 HashMap 实现图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34664134/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com