2

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

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

1 回答 1

0

您在构造函数中定义了一个与类变量同名的局部变量“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
    }

}
于 2019-11-15T15:39:17.840 回答