[Lintcode] 105. Copy List with Random Pointer

給出一個鏈表,每個節點包含一個額外增加的隨機指針可以指向鏈表中的任何節點或空的節點。

返回一個深拷貝的鏈表。

public class Solution {  
    public RandomListNode copyRandomList(RandomListNode head) {  
        if (head == null) {  
            return null;  
        }  
          
        HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();  
        RandomListNode dummy = new RandomListNode(0);  
        RandomListNode pre = dummy, newNode;  
        while (head != null) {  
            if (map.containsKey(head)) {  
                newNode = map.get(head);  
            } else {  
                newNode = new RandomListNode(head.label);  
                map.put(head, newNode);  
            }  
            pre.next = newNode;  
              
            if (head.random != null) {  
                if (map.containsKey(head.random)) {  
                    newNode.random = map.get(head.random);  
                } else {  
                    newNode.random = new RandomListNode(head.random.label);  
                    map.put(head.random, newNode.random);  
                }  
            }  
              
            pre = newNode;  
            head = head.next;  
        }  
          
        return dummy.next;  
    }  
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章