《劍指offer第二版》面試題18:刪除鏈表的節(jié)點(diǎn)(java)

題目描述

給定單向鏈表的頭指針和一個(gè)節(jié)點(diǎn)指針,定義一個(gè)函數(shù)在O(1)時(shí)間內(nèi)刪除該節(jié)點(diǎn)。

解題思路:

  1. 可以要?jiǎng)h除的節(jié)點(diǎn)A的下一個(gè)節(jié)點(diǎn)B的值復(fù)制到當(dāng)前節(jié)點(diǎn),再刪除節(jié)點(diǎn)B,即可實(shí)現(xiàn)在O(1)時(shí)間內(nèi)刪除節(jié)點(diǎn)。
  2. 如果要?jiǎng)h除的節(jié)點(diǎn)A就是頭節(jié)點(diǎn),則將頭節(jié)點(diǎn)置為null即可。
  3. 如果要?jiǎng)h除的節(jié)點(diǎn)A是最后一個(gè)節(jié)點(diǎn),則仍然需要使用遍歷的方式。

代碼

ListNode deleteNode(ListNode head, ListNode nodeToBeDel) {
    if (head == null ) {
        return null;
    }
    if (nodeToBeDel == null) {
        return head;
    }
    if (nodeToBeDel.next != null) {
        // 被刪除的是中間節(jié)點(diǎn)
        nodeToBeDel.value = nodeToBeDel.next.value;
        nodeToBeDel.next = nodeToBeDel.next.next;
    } else if (head == nodeToBeDel) {
        // 被刪除的是頭節(jié)點(diǎn)
        head = null;
    }else {
        // 被刪除的是尾部節(jié)點(diǎn)
        ListNode node = head;
        while (node.next != nodeToBeDel) {
            node = node.next;
        }
        node.next = null;
    }
    return head;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容