Help! Why the StackOverFlowError could be removed by changing HashMap to Map?


  • 0
    A

    I am really confused by the problem as following, and really need help. Thank you.
    My first version for this Copy List with Random Pointer problem is as following:

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

    }

    But this give me a Runtime Error Message: Line 17: java.lang.StackOverflowError
    Line 17 is: if (map.containsKey(node)) return map.get(node);

    However, after I changed the 1st line: HashMap<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();
    to Map<RandomListNode, RandomListNode> map = new HashMap<RandomListNode, RandomListNode>();

    the code was accepted.
    But what I changed is just from HashMap to Map, how this error get removed? Why using Map instead of HashMap help prevent the stackoverflow error? I am really confused. Who can help me solve it? Thank you so much.


Log in to reply
 

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