我必须为一个类创建一个链表数组,以便存储一个图(邻接表)。我们必须使用Java。我可以创建数组并实例化每个链表,但是当我将第一个元素添加到每个链表时,每个 链表都会发生变化,而不仅仅是数组索引处的链表。
Node [] adjList;
for(i=0;i<adjList.length;i++)
adjList[i] = new Node(0,0,null);
这会实例化每个新的链表 [Node
是我自己的类,带有构造函数 Node(int head, int data, Node next
) 并扩展 LinkedList
]
然后我将第一个值添加到每个节点:
for(i=0;i<adjList.length;i++)
adjList[i].setHead(i+1); // numbers 1 to end are the graph vertices
或
for(i=0;i<adjList.length;i++)
adjList[i].add(new Node(i+1,0,null);
我使用打印语句来调试代码 在这些循环的末尾,我打印出每个链接列表,但是对于每个链接列表,值都是最终值
即。如果 adjList.length = 2
,它会打印出
[3,0,null] // adjList[0]
[3,0,null] // adjList[1]
[3,0,null] // adjList[2]
编辑:这里是 Node 类
import java.util.LinkedList;
public class Node extends LinkedList{
private static int head;
private static int data;
private static Node next;
public Node(int h,int d,Node n) {
head = h;
data = d;
next = n;
}
public int getHead(){ // getNext() and getData() are the same
return head;
}
public void setHead(int h){ // setNext() and setData() are basically the same
head = h;
}
}
最佳答案
您可能已将 Node
中的某些内容声明为静态的,因此每个实例最终都具有相同的共享值,而不是拥有自己的值。然而,这只是一个猜测 - 请发布 Node
的代码,以便我们了解问题的真正原因......
关于java - Java 中的链表数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9659160/