《劍指 offer》 學習25之複雜鏈表的複製

題目描述

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

題目鏈接:牛客網

解題思路

第一步,在每個節點的後面插入複製的節點。
image.png

第二步,對複製節點的 random 鏈接進行賦值。
image.png

第三步,拆分。
image.png

/*
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 cur = pHead;
	    while (cur != null) {
	        RandomListNode clone = new RandomListNode(cur.label);
	        clone.next = cur.next;
	        cur.next = clone;
	        cur = clone.next;
	    }
	    
	    // 建立 random 連接
	    cur = pHead;
	    while (cur != null) {
	        RandomListNode clone = cur.next;
	        if (cur.random != null) {
	            clone.random = cur.random.next;
	        } 
	        cur = clone.next;
	    }
	    
	    // 拆分
	    cur = pHead;
	    RandomListNode cloneHead = pHead.next;
	    while (cur.next != null) {
	        RandomListNode next = cur.next;
	        cur.next = next.next;
	        cur = next;
	    }
	    
	    return cloneHead;
    }
}

測試結果

image.png

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