劍指Offer Java版 面試題35:復(fù)雜鏈表的復(fù)制

題目:輸入一個(gè)復(fù)雜鏈表(每個(gè)節(jié)點(diǎn)中有節(jié)點(diǎn)值,以及兩個(gè)指針,一個(gè)指向下一個(gè)節(jié)點(diǎn),另一個(gè)特殊指針指向任意一個(gè)節(jié)點(diǎn)),返回結(jié)果為復(fù)制后復(fù)雜鏈表的head。

練習(xí)地址

https://www.nowcoder.com/practice/f836b2c43afc4b35ad6adc41ec941dba
https://leetcode-cn.com/problems/fu-za-lian-biao-de-fu-zhi-lcof/

參考答案

/*
public class RandomListNode {
    int label;
    RandomListNode next = null;
    RandomListNode random = null;

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
public class Solution {
    public RandomListNode Clone(RandomListNode pHead) {
        if (pHead == null) {
            return null;
        }
        cloneNodes(pHead);
        connectRandomNodes(pHead);
        return reconnectNodes(pHead);
    }
    
    private void cloneNodes(RandomListNode head) {
        // 根據(jù)原始鏈表的每個(gè)節(jié)點(diǎn) N 創(chuàng)建對(duì)應(yīng)的 N'
        RandomListNode node = head;
        while (node != null) {
            RandomListNode cloned = new RandomListNode(node.label);
            cloned.next = node.next;
            node.next = cloned;
            node = cloned.next;
        }
    }
    
    private void connectRandomNodes(RandomListNode head) {
        // 設(shè)置復(fù)制出來的節(jié)點(diǎn)的 random
        RandomListNode node = head, cloned;
        while (node != null) {
            cloned = node.next;
            if (node.random != null) {
                cloned.random = node.random.next;
            }
            node = cloned.next;
        }
    }
    
    private RandomListNode reconnectNodes(RandomListNode head) {
        // 把這個(gè)長(zhǎng)鏈表拆分成兩個(gè)鏈表
        RandomListNode node = head, clonedHead = head.next, cloned;
        while (node != null) {
            cloned = node.next;
            node.next = cloned.next;
            if (node.next != null) {
                cloned.next = node.next.next;
            }
            node = node.next;
        }
        return clonedHead;
    }
}

復(fù)雜度分析

  • 時(shí)間復(fù)雜度:O(n)。
  • 空間復(fù)雜度:O(1)。

??劍指Offer Java版目錄
??劍指Offer Java版專題

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

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

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