O(1)時(shí)間內(nèi)刪除單向鏈表中的一個(gè)節(jié)點(diǎn)

給定單向鏈表的頭指針和一個(gè)結(jié)點(diǎn)指針,定義一個(gè)函數(shù)在O(1)時(shí)間刪除該結(jié)點(diǎn)
錯(cuò)誤思路:從鏈表結(jié)點(diǎn)開始,循序便利查找要?jiǎng)h除的結(jié)點(diǎn),并在鏈表刪除結(jié)點(diǎn)
正確思路:已知要?jiǎng)h除的結(jié)點(diǎn)可得下一個(gè)結(jié)點(diǎn),那么我們可以將下一個(gè)結(jié)點(diǎn)內(nèi)容復(fù)制到當(dāng)前結(jié)點(diǎn)。同時(shí)注意首位結(jié)點(diǎn)

 public static void delete(ListNode head,ListNode target){
        if(head==null||target==null){
            return;
        }
        if(head.getNext()==null){
            if(head==target){
                head=null;
            }else{
                return;
            }
        }
        if(target.getNext()==null){
            ListNode currentNode = head;
      
            while(currentNode.getNext()!=null){
                currentNode = currentNode.getNext();
            }
            currentNode.setNext(null);
        }
        if(target.getNext()!=null){
            target.setValue(target.getNext().getValue());
            if(target.getNext().getNext()!=null){
                target.setNext(target.getNext().getNext());
            }else{
                target.setNext(null);
            }
        }
    }

原文鏈接:http://blog.csdn.net/qq_22329521/article/details/53164557

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • 轉(zhuǎn)載請注明出處:http://www.itdecent.cn/p/c65d9d753c31 在上一篇博客《數(shù)據(jù)結(jié)構(gòu)...
    Alent閱讀 3,600評論 4 74
  • 【聲明】歡迎轉(zhuǎn)載,但請保留文章原始出處→_→文章來源:http://www.itdecent.cn/p/08d08...
    夢工廠閱讀 3,851評論 3 31
  • Java8張圖 11、字符串不變性 12、equals()方法、hashCode()方法的區(qū)別 13、...
    Miley_MOJIE閱讀 3,899評論 0 11
  • 鏈表是線性表的鏈?zhǔn)酱鎯?chǔ)方式,邏輯上相鄰的數(shù)據(jù)在計(jì)算機(jī)內(nèi)的存儲(chǔ)位置不一定相鄰,那么怎么表示邏輯上的相鄰關(guān)系呢? 可以...
    rainchxy閱讀 2,252評論 0 6
  • B樹的定義 一棵m階的B樹滿足下列條件: 樹中每個(gè)結(jié)點(diǎn)至多有m個(gè)孩子。 除根結(jié)點(diǎn)和葉子結(jié)點(diǎn)外,其它每個(gè)結(jié)點(diǎn)至少有m...
    文檔隨手記閱讀 13,683評論 0 25

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