这是我书中的一个例子。正如我所见,当您使用此类创建列表时,您创建了两个对象(first
和 last
,均为 null)。当您将第一个和最后一个“Node”对象放入 add 方法中时,我不明白为什么。当您同时设置 first = n
和 last = n
时,它不应该创建两个元素吗?例如,如果我调用 list.add(2)
,那么 first
和 last
现在不应该都是 2 吗?
public class List {
private Node first = null;
private Node last = null;
public List(){
first = null;
last = null;
}
private static class Node{
public int value;
public Node next;
public Node ( int value, Node next){
this.value = value;
this.next = next;
}
}
public void add (int value){
Node n = new Node (value,null);
if(first==null){
first = n;
last = n;
}else{
last.next = n;
last = n;
}
}
public int size(){
int number = 0;
Node n = first;
while(n != null){
number++;
n = n.next;
}
return number;
}
}
最佳答案
As i see it, when u create a list with this class, you create two objects (first and last, which are null).
这不是真的。 first
和 last
不是对象,而是对对象的引用。在本例中,它们以 null 引用开始,这意味着它们根本不引用任何对象。
当你写 first = n; 时last = n;
,您将 first
和 last
设置为都引用同一个对象 - 无论 n
引用什么对象。
For example, if list.add(2), shouldn't now both first and last be 2?
是的,它们都引用同一个 Node
实例,其 value
为 2。
关于java - 在Java中构建链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8931461/