【发布时间】:2019-09-30 20:48:42
【问题描述】:
我不明白为什么下面的方法有效。顾名思义,它删除了链接列表中的所有空值,列表的前面称为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;
}
}
}
【问题讨论】:
-
需要更多关于 head 变量的信息。是否维护深层副本?
-
@YogeshKaushik 不,我不这么认为。
标签: java list linked-list