牛客網:複雜鏈表的複製

題目描述:

輸入一個複雜鏈表(每個節點中有節點值,以及兩個指針,一個指向下一個節點,另一個特殊指針指向任意一個節點),返回結果爲複製後複雜鏈表的head。(注意,輸出結果中請不要返回參數中的節點引用,否則判題程序會直接返回空)

思路:

  1. 複製並插入:複製舊鏈表的每個結點,如:複製A得到A1,將A1插入A的後面;
  2. 遍歷鏈表,補充新結點的 random 域,如: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 oldCur = pHead;
        //1.複製並插入
        while(oldCur != null){
            RandomListNode newNode = new RandomListNode(oldCur.label);

            newNode.next = oldCur.next;
            oldCur.next = newNode;
            oldCur = newNode.next;
        }
        oldCur = pHead;
        //2.修改新鏈表的random域
        while(oldCur != null){
            RandomListNode newCur = oldCur.next;
            if(oldCur.random != null) {
                newCur.random = oldCur.random.next;
            }
            oldCur = newCur.next;

        }
        //3.拆分
        oldCur = pHead;
        RandomListNode res = pHead.next;
        RandomListNode tmp = oldCur.next;
        while(oldCur.next != null){
            oldCur.next = tmp.next;
            oldCur = tmp;
            tmp = tmp.next;
        }
        return res;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章