返回头部如何给我链接列表中的结果
在以下代码中,该方法返回了我的数组头,该数组的引用是LinkedList的头部,并带有删除的重复项。我无法考虑的是,当所有指针更改当前时,头部如何包含该参考。
public static Node removeDuplicates(Node head)
{
Node previous = null;
Node current = head;
// take an empty set to store linked list nodes for future reference
Set<Integer> set = new HashSet<>();
// do till the linked list is empty
while (current != null)
{
// if the current node is seen before, ignore it
if (set.contains(current.data)) {
previous.next = current.next;
}
else {
// insert the current node into the set and proceed to the next node
set.add(current.data);
previous = current;
}
current = previous.next;
}
return head;
}
In the following code, the method returns me the head of the array which is reference of the head of the linkedlist with removed duplicates. What I can't get mind around is how does the head contain that reference when all the pointer changes has been made on current.
public static Node removeDuplicates(Node head)
{
Node previous = null;
Node current = head;
// take an empty set to store linked list nodes for future reference
Set<Integer> set = new HashSet<>();
// do till the linked list is empty
while (current != null)
{
// if the current node is seen before, ignore it
if (set.contains(current.data)) {
previous.next = current.next;
}
else {
// insert the current node into the set and proceed to the next node
set.add(current.data);
previous = current;
}
current = previous.next;
}
return head;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
考虑从
head
开始的链接列表遍历列表,我们以该顺序获得
a,b,c,d
。令
当前
为b
,然后删除下一个节点(即c
),因此b.next = d
。现在,列表开始遍历列表现在将打印
a,b,d
。更改是在b
中进行的,但是由于a
具有对b
的引用,因此在b
后进行的任何更改代码>将反映在a
开始的遍历中。Consider the linked list
Traversing the list, starting at
head
, we getA,B,C,D
in that order.Let
current
beB
, and you remove the next node (ie.C
), soB.next = D
. The list now becomesTraversing the list would now print
A,B,D
. The change was made inB
, but since theA
holds a reference toB
, any changes made in and afterB
would be reflected in the traversal starting atA
.