亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么操作 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 關注
  • 87 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號