为什么要操作LinkedList节点别名使该方法起作用?

问题描述 投票:0回答:1

我不明白以下方法为何有效。顾名思义,它将删除链接列表中的所有空值,列表的最前面称为head。我了解到head变量的别名是使用Node<E> current = head创建的,但是我无法弄清楚该方法如何设法维护原始的head变量。从外观上看,每次迭代都会使电流越来越小(current = current.nextcurrent.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;
            System.out.println("head: " + head.data + ", current: " + current.data);
        }
    }
}
java list linked-list
1个回答
0
投票

我知道head变量的别名是使用Node<E> current = head

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

© www.soinside.com 2019 - 2024. All rights reserved.