首页 > 解决方案 > 添加边的加权有向图不起作用

问题描述

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

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

标签: javagraphgraph-theoryweightedweighted-graph

解决方案


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

}

推荐阅读