Java recursive solution


  • 2
    L
    Map<Integer,RandomListNode> cache = new HashMap<>();
    public RandomListNode copyRandomList(RandomListNode node) {
        if(node == null) return null;
        if(cache.containsKey(node.label)) return cache.get(node.label);
        RandomListNode rln = new RandomListNode(node.label);
        cache.put(node.label,rln);
        rln.next = copyRandomList(node.next);
        rln.random = copyRandomList(node.random);
        return rln;
    }

  • 0
    F

    The prerequisite should be : The labels in the RandomListNode cannot duplicate.


  • 0
    A

    Why if I changed it to HashMap<Integer, RandomListNode>, it will stackoverflow?

    HashMap<Integer, RandomListNode> cache = new HashMap<>();
    public RandomListNode copyRandomList(RandomListNode node) {
        if (node == null) {
            return null;
        }
        if (cache.containsKey(node.label)) {
            return cache.get(node.label);
        }
        RandomListNode rln = new RandomListNode(node.label);
        cache.put(rln.label, rln);
        rln.next = copyRandomList(node.next);
        rln.random = copyRandomList(node.random);
        return rln;
    }

Log in to reply
 

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