【问题标题】:Weighted directed graph adding an edge not working添加边的加权有向图不起作用
【发布时间】:2019-11-15 15:07:08
【问题描述】:

您好,我在使用所选代码时遇到问题。 谁能告诉我为什么粗体部分不起作用?

    Graph(int vertices) {
        int vertices;
        LinkedList<Edge> [] adjacencylist;

        this.vertices = vertices;
        adjacencylist = new LinkedList[vertices];
        //initialize adjacency lists for all the vertices
        for (int i = 0; i < vertices ; i++) {
            adjacencylist[i] = new LinkedList<>();
        }
    }

    public void addEgde(String source, String destination, int weight) {
        Edge edge = new Edge(source, destination, weight);
        **adjacencylist[source].addFirst(edge); //for directed graph**
    }

【问题讨论】:

  • 你有两个变量adjacencylist,一个在类中,一个在构造函数的范围内?
  • 变量顶点和邻接列表在一个名为“Graph”的静态类中声明,就在我发布的代码清单之前
  • Java 中没有 static class 这样的东西。如果答案是“是”,我希望通过我的评论让你自己意识到你的错误
  • 任何数组都以整数为索引。您在 addEgde 方法中使用字符串作为索引。
  • 如果我需要源是字符串而不是 int,解决方案是什么? parseInt 会起作用吗?

标签: java graph graph-theory weighted weighted-graph


【解决方案1】:

您在构造函数中定义了一个与类变量同名的局部变量“adjacencyList”。局部变量覆盖类变量并且类变量保持为空。此外,源参数不能用作数组的索引。必须是整数。

public class Graph {

    int vertices;
    private LinkedList<Edge> [] adjacencylist;

    Graph(int vertices) {

        this.vertices = vertices;
        adjacencylist = new LinkedList[vertices];
        //initialize adjacency lists for all the vertices
        for (int i = 0; i < vertices ; i++) {
            adjacencylist[i] = new LinkedList<>();
        }
    }

    public void addEgde(int source, String destination, int weight) {
        Edge edge = new Edge(source, destination, weight);
        adjacencylist[source].addFirst(edge); //for directed graph
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2022-01-02
    • 1970-01-01
    • 2020-05-19
    • 2011-12-22
    相关资源
    最近更新 更多