Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 为什么操纵LinkedList节点别名允许此方法工作?_Java_List_Linked List - Fatal编程技术网

Java 为什么操纵LinkedList节点别名允许此方法工作?

Java 为什么操纵LinkedList节点别名允许此方法工作?,java,list,linked-list,Java,List,Linked List,我不明白为什么下面的方法有效。顾名思义,它删除链接列表中的所有空值,列表的前面称为head。我知道head变量的别名是用Node current=head创建的,但我不知道该方法如何维护原始head变量。从外观上看,每次迭代都会使当前值越来越小(current=current.next或current.next=current.next.next),但不知何故,打印链表时,一个完全完整且准确的head变量仍然存在。我相信这个答案一定很简单,但我想不通 public void remove_nul

我不明白为什么下面的方法有效。顾名思义,它删除链接列表中的所有空值,列表的前面称为
head
。我知道
head
变量的别名是用
Node current=head
创建的,但我不知道该方法如何维护原始head变量。从外观上看,每次迭代都会使当前值越来越小(
current=current.next
current.next=current.next.next
),但不知何故,打印链表时,一个完全完整且准确的
head
变量仍然存在。我相信这个答案一定很简单,但我想不通

public void remove_nulls() {
    while (head!=null && head.data==null) {
        removeFirst();
    }
    if (head==null) {
        return;
    }
    // List is non-empty and does not start with a null item
    Node<E> current=head;
    while (current.next!=null) {
        if (current.next.data==null) {
            current.next=current.next.next;
            size--;
        } else {
            current = current.next;

        }
    }
}
public void remove_nulls(){
while(head!=null&&head.data==null){
移除第一个();
}
if(head==null){
回来
}
//列表不为空,且不以空项开头
节点电流=头;
while(current.next!=null){
if(current.next.data==null){
current.next=current.next.next;
大小--;
}否则{
当前=当前。下一步;
}
}
}
我知道head变量的别名是用
Node current=head

此语句不正确,因为
current
不是“别名”,它是指向与
head
相同地址的新引用。因此,当您重新分配
current=current.next
时,
head
引用不会更改,它仍将指向它所指向的地址,
current
将指向下一个元素

换句话说,如果列表的第一个元素不是
null
,则
head
引用将不会更改,并且在方法完成时仍将指向相同的元素。所有其他
null
元素通过此行删除:
current.next=current.next.next


需要更多关于head变量的信息。它是在维护一个深度副本吗?@YogeshKaushik不,我不这么认为。那么,head变量是如何修改的呢?此方法完成后,这些更改将反映在列表中。@您的意思是如何修改列表的head元素?我认为它发生在
removeFirst()
方法中。只有在第一个元素的数据为null@TheFiveHundredYears正确,如果第一个元素的数据不为null,则不应修改它,对吗?不,该方法将删除所有null,因此将删除中间的null元素。