劍指Offer_編程題_複雜鏈表的複製

考點:分解讓複雜問題簡單java

https://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba?f=discussiondom

題目描述

輸入一個複雜鏈表(每一個節點中有節點值,以及兩個指針,一個指向下一個節點,另外一個特殊指針random指向一個隨機節點),請對此鏈表進行深拷貝,並返回拷貝後的頭結點。(注意,輸出結果中請不要返回參數中的節點引用,不然判題程序會直接返回空)
 

解題思路

 

 

連接: https://www.nowcoder.com/questionTerminal/f836b2c43afc4b35ad6adc41ec941dba?f=discussion
來源:牛客網

/*
*解題思路:
* 1 、遍歷鏈表,複製每一個結點,如複製結點A獲得A1,將結點A1插到結點A後面;
* 2 、從新遍歷鏈表,複製老結點的隨機指針給新結點,如A1.random = A.random.next;
* 3 、拆分鏈表,將鏈表拆分爲原鏈表和複製後的鏈表
*/
 
/*
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;
        }
         
        RandomListNode currentNode = pHead;
        //一、複製每一個結點,如複製結點A獲得A1,將結點A1插到結點A後面;
        while(currentNode != null){
            RandomListNode cloneNode = new RandomListNode(currentNode.label);
            RandomListNode nextNode = currentNode.next;
            currentNode.next = cloneNode;
            cloneNode.next = nextNode;
            currentNode = nextNode;
        }
         
        currentNode = pHead;
        //二、從新遍歷鏈表,複製老結點的隨機指針給新結點,如A1.random = A.random.next;
        while(currentNode != null) {
            currentNode.next.random = currentNode.random==null?null:currentNode.random.next;
            currentNode = currentNode.next.next;
        }
         
        //三、拆分鏈表,將鏈表拆分爲原鏈表和複製後的鏈表
        currentNode = pHead;
        RandomListNode pCloneHead = pHead.next;
        while(currentNode != null) {
            RandomListNode cloneNode = currentNode.next;
            currentNode.next = cloneNode.next;
            cloneNode.next = cloneNode.next==null?null:cloneNode.next.next;
            currentNode = currentNode.next;
        }
         
        return pCloneHead;
    }
}
相關文章
相關標籤/搜索