Copy List with Random Pointer (Java)

A linked list is given such that each node contains an additional random pointer which could point to any node in the list or null.

Return a deep copy of the list.

這道題和clone graph那道題不同的地方在於,圖可以dfs完成搜索,即直接判斷node的neighbor是否在hashmap中,如果沒有就加入並從此neighbor開始新的dfs遞歸,而鏈表如果根據random是否已經加入hashmap來判斷的話,遍歷會出現問題。所以只能先將所有的新舊鏈表都加入hashmap再遍歷一遍進行random的賦值。尤其注意,複製品的random必須是複製品,不能是正品,即直接把正品的random賦值給複製品。

Source

/**
 * Definition for singly-linked list with a random pointer.
 * class RandomListNode {
 *     int label;
 *     RandomListNode next, random;
 *     RandomListNode(int x) { this.label = x; }
 * };
 */
public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        if(head == null)
        	return null;
        HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
        RandomListNode a = new RandomListNode(head.label);
        map.put(head, a);
        
        RandomListNode p = head.next;
        RandomListNode newhead = a;
        while(p != null){
        	RandomListNode b = new RandomListNode(p.label);
        	map.put(p, b);
        	a.next = b;
        	
        	p = p.next;
        	a = a.next;
        }
        
        p = head;
        a = newhead;
        while(p != null){
        	a.random = map.get(p.random);  //p.random的複製品賦給複製品的random
        	p = p.next;
        	a = a.next;
        }
        return newhead;
    }
}


Test

    public static void main(String[] args){
    	RandomListNode a = new RandomListNode(1);
    	a.next = new RandomListNode(2);
    	a.next.next = new RandomListNode(3);
    	a.next.next.next = new RandomListNode(4);
    	a.next.next.next.next = new RandomListNode(5);
    	a.next.random = a.next.next.next;
    	
    	RandomListNode b = new Solution().copyRandomList(a);
    	while(b != null){
    		if(b.random == null) System.out.println("null");
    		else System.out.println(b.random.label);
    		b = b.next;
    	}
    }


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