Monday, June 2, 2014

Copy List with Random Pointer

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.

遇到类似树或图形状的,一定先考虑递归,因为真的差很大!!!! 可以实现和快速简单实现真的差很大!!!!

这个题只要用hashmap跟踪就好了...

public class Solution {
    public RandomListNode copyRandomList(RandomListNode head) {
        HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
        return copying(head, map);
    }
    
    public RandomListNode copying(RandomListNode head, HashMap<RandomListNode, RandomListNode> map){
        if(head ==null) return null;
        if(!map.containsKey(head)){
            RandomListNode newNode = new RandomListNode(head.label);
            map.put(head, newNode);
            newNode.next = copying(head.next, map);
            newNode.random = copying(head.random, map);
            return newNode;
        }else
            return map.get(head);
    }
}

No comments:

Post a Comment