Java AC solution. Is this a special case of the problem "clone graph"?


  • 0
    D
    public class Solution {
        HashMap<RandomListNode,RandomListNode> copied;
        public RandomListNode dfs(RandomListNode head)
        {
            if(head==null)
                return null;
            if(copied.containsKey(head))
                return copied.get(head);
            RandomListNode copyOfHead=new RandomListNode(head.label);
            copied.put(head,copyOfHead);
            if(head.next!=null)
                copyOfHead.next=dfs(head.next);
            if(head.random!=null)
                copyOfHead.random=dfs(head.random);
            return copyOfHead;
        }
        public RandomListNode copyRandomList(RandomListNode head) {
            if(head==null)
                return null;
            else
            {
                copied=new HashMap<RandomListNode,RandomListNode>();
                return dfs(head);
            }
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.