我需要一些帮助来理解方法的工作原理。对Java链接列表中的节点的引用
我有这样的决定的基本Node
类:
class Node {
Node next = null;
int data;
public Node(int d){
data = d;
}
}
现在我期待在如何deleteDuplicates
方法工作。我知道我们迭代地遍历每个节点并将其值存储在一个集合中。如果该值已经在该集合中,我相信我们将前一节点的next
指针设置为跳过当前节点。这里的方法:
public static Node deleteDuplicates(Node head){
Node n = head;
HashSet<Integer> set = new HashSet<Integer>();
Node previous = null;
while(n != null) {
if (set.contains(n.data)){
// skip this node
previous.next = n.next;
}
else {
set.add(n.data);
previous = n;
}
n = n.next;
}
return head;
}
我感到困惑的变量previous
和n
。当我们设置previous = n;
时,是不是让它们引用同一个对象?如果他们引用同一个对象,则对n
所做的更改将与previous
中的相同。那么线previous.next = n.next;
是如何工作的?
谢谢!
不应该'previous.next = n.next;'是'previous = n.next;'? – c0der
@ c0der它似乎是正常的,但仍然不能解释参考问题 –
我问它,因为它看起来这种方法是错误的。当'previous'为'null'时使用'previous.next'就是一个例子, – c0der