我不明白以下方法为何有效。顾名思义,它将删除链接列表中的所有空值,列表的最前面称为head
。我了解到head
变量的别名是使用Node<E> 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;
System.out.println("head: " + head.data + ", current: " + current.data);
}
}
}
我知道head变量的别名是使用
Node<E> current = head
此语句是不正确的,因为current
不是'别名',它是指向与head
相同地址的新引用。因此,当您重新分配current = current.next
时,head
引用不会更改,它仍将指向其指向的地址,而current
将指向下一个元素。