Wednesday, January 29, 2014

Leetcode: 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.

Solution

/**
 * 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) {
        return copyRandomList(head, new HashMap<RandomListNode, RandomListNode>());
    }
    
    public RandomListNode copyRandomList(RandomListNode head, HashMap<RandomListNode, RandomListNode> cloned)
    {
        if(head == null)
            return null;
        if(cloned.containsKey(head))
            return cloned.get(head);
        RandomListNode node = new RandomListNode(head.label);
        cloned.put(head, node);
        node.next = copyRandomList(head.next, cloned);
        node.random= copyRandomList(head.random, cloned);
        return node;
    }
}

No comments :

Post a Comment