java - 添加边的加权有向图不起作用
问题描述
嗨,我在使用所选代码时遇到问题。谁能告诉我为什么粗体部分不起作用?
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”。局部变量覆盖类变量并且类变量保持为空。此外,源参数不能用作数组的索引。它必须是一个整数。
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
}
}
推荐阅读
- django - 带有外部存储的 url.py settings.py 和 Dropbox
- python-3.x - Django - 表单未保存到 Db
- r - 选择具有多个 if 和 if else 语句的行 (R)
- javascript - 执行 php 脚本后的 JavaScript 警报窗口
- r - 使用 NA 和 R 中其他变量的值进行变异和 ifelse
- reactjs - Firebase 有反应问题
- apache-spark - Pyspark 代码改进思路(降低持续时间)
- node.js - GitLab 在部署 dockerized node.js 应用程序时不断加载并最终失败
- javascript - 如何垂直对齐``s 并排没有`float`?
- reactjs - 如何修复 react 和 laravel 项目中的 cors 错误