首页 > 解决方案 > 如何连接邻接列表中的 2 个顶点?

问题描述

我正在尝试学习不同的数据结构,我目前正在努力学习图表。

我正在尝试使用链接列表映射来实现邻接列表。这使我能够搜索顶点的名称并快速查看其所有连接。

但我在实际添加任何连接时遇到了麻烦。我目前正在做的是

   public void add(V vertexName) {
    if (!contains(vertexName)) {
        ArrayList<V> array = new ArrayList<>(); 
        adjList.put(vertexName,array);
    }

}

public void connect(V start, V destination) {
if (!contains(start) || !contains(destination))
    throw new NoSuchElementException();
adjList.get(start).add(destination); //adds destination to starts arraylist

}

System.out.print(adjList.toString);

但是,例如,如果我将 12、10 和 20 添加到我的列表中,然后连接 20 和 12,我仍然会得到:

12

10

20

代替

12

10

20 - > 12

任何提示将不胜感激。如果有帮助,adjList 是一个

Map<V,ArrayList<V>> adjList;

我只是想从一个有向未加权图开始,以使事情变得更容易

标签: java

解决方案


推荐阅读