1. 程式人生 > >《劍指offer》系列 複雜連結串列的複製(Java)

《劍指offer》系列 複雜連結串列的複製(Java)

連結

牛客: 複雜連結串列的複製

題目描述

輸入一顆二叉樹的跟節點和一個整數,打印出二叉樹中結點值的和為輸入整數的所有路徑。路徑定義為從樹的根結點開始往下一直到葉結點所經過的結點形成一條路徑。(注意: 在返回值的list中,陣列長度大的陣列靠前)

思路

這題目應該算是這本書最難得幾個題目之一了,主要是思路很難想到。
具體思路可見 java 複雜連結串列的複製

程式碼

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

    RandomListNode(int label) {
        this.label = label;
    }
}
*/
public class Solution {
    //第一步 在原連結串列每個結點後面分別複製建立新的結點
    public static void cloneNodes(RandomListNode pHead) {
        RandomListNode pNode = pHead;
        while (pNode != null) {
            RandomListNode pCloned = new RandomListNode(0);
            pCloned.label = pNode.label;
            pCloned.next = pNode.next;
            pCloned.random = null;

            pNode.next = pCloned;
            pNode = pCloned.next;
        }
    }

    //第二步 根據舊連結串列的兄弟結點 初始化新連結串列的兄弟結點
    public static void connectRandom(RandomListNode pHead) {
        RandomListNode pNode = pHead;
        while (pNode != null) {
            RandomListNode pCloned = pNode.next;
            if (pNode.random != null) {
                pCloned.random = pNode.random.next;
            }
            pNode = pCloned.next;
        }
    }

    //第三步 從舊連結串列拆分得到新的結點
    public static RandomListNode reconnectNode(RandomListNode pHead) {
        RandomListNode pNode = pHead;
        RandomListNode pClonedHead = null;
        RandomListNode pClonedNode = null;

        if (pNode != null) {
            pClonedHead = pClonedNode = pNode.next;
            pNode.next = pClonedNode.next;
            pNode = pNode.next;
        }

        while (pNode != null) {
            pClonedNode.next = pNode.next;
            pClonedNode = pClonedNode.next;
            pNode.next = pClonedNode.next;
            pNode = pNode.next;
        }
        return pClonedHead;
    }

    //分為三個步驟
    //第一步 在原連結串列每個結點後面分別複製建立新的結點
    //第二步 根據舊連結串列的兄弟結點 初始化新連結串列的兄弟結點
    //第三步 從舊連結串列拆分得到新的結點
    public static RandomListNode Clone(RandomListNode pHead) {
        cloneNodes(pHead);
        connectRandom(pHead);
        return reconnectNode(pHead);
    }
}