gpt4 book ai didi

java - LinkedList Array 中每个索引的 LinkedList

转载 作者:行者123 更新时间:2023-12-02 11:23:33 26 4
gpt4 key购买 nike

这里有什么问题?。我正在尝试使用邻接列表,通过利用 util 包中的集合来实现图形数据结构。这里

LinkedList array which holds some integer. Each element of that LinkedList holds another LinkedList of type: node.

但是在编译过程中,却提示类型不兼容。如何解决这个问题?

 //Sum of dependencies in a graph
import java.util.*;
class node
{
int vertex,weight;
public node(int v,int w)
{
vertex = v;
weight = w;
}
}
public class dependency
{
int V;
LinkedList<Integer> adj[];
public dependency(int v)
{
V = v;
adj = new LinkedList<Integer>[v];
for (int i=0;i < v ;i++ ) {
adj[i] = new LinkedList<node>();
}
}
void addEdge(int v,node l)
{
adj[v].add(l);
}
void BFS(int s)
{
boolean visited[] = new boolean[V];
LinkedList<Integer> queue = new LinkedList<Integer>();
visited[s] = true;
queue.add(s);
while(queue.size() != 0)
{
s = queue.poll();
System.out.println(s+" ");

Iterator<Integer> i = adj[s].listIterator();
while(i.hasNext())
{
int n = i.next();
if(!visited[n])
{
visited[n] = true;
queue.add(n);
}
}
}
}
public static void main(String[] args) {
graph g = new graph(4);
node a = new node(1,10);
node b = new node(2,20);
node c = new node(2,30);
node d = new node(0,20);
node e = new node(3,30);
node f = new node(3,20);
g.addEdge(0, a);
g.addEdge(0, b);
g.addEdge(1, c);
g.addEdge(2, d);
g.addEdge(2, e);
g.addEdge(3, f);

System.out.println("Following is Breadth First Traversal "+
"(starting from vertex 2)");

g.BFS(2);
}
}

最佳答案

您已经声明了类型为 LinkedList<Integer> 的 LinkedList 数组。 ,但您正在尝试存储 LinkedList<node>在数组中。您似乎从未使用过 weight node 的属性,所以你应该改变 adj[i] = new LinkedList<node>();adj[i] = new LinkedList<Integer>(); .

关于java - LinkedList Array 中每个索引的 LinkedList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49761282/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com