为了账号安全,请及时绑定邮箱和手机立即绑定

为什么操作 LinkedList 节点别名可以让这个方法起作用?

为什么操作 LinkedList 节点别名可以让这个方法起作用?

炎炎设计 2023-09-13 18:08:42
我不明白为什么下面的方法有效。顾名思义,它删除链接列表中的所有空值,列表的前面称为head。我知道该变量的别名head是使用 创建的Node<E> current = 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;        }    }}
查看完整描述

1 回答

?
慕码人8056858

TA贡献1803条经验 获得超6个赞

我知道 head 变量的别名是用以下命令创建的 Node<E> current = head

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

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

https://img1.sycdn.imooc.com//65018a5600011a0405570297.jpg

查看完整回答
反对 回复 2023-09-13
  • 1 回答
  • 0 关注
  • 40 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信