加权有向图添加边不起作用

时间:2019-11-15 15:07:08

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

您好,我在选择代码时遇到了麻烦。 谁能告诉我找出为什么粗体部分无法正常工作?

    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**
    }

1 个答案:

答案 0 :(得分:0)

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

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
    }

}