Check if two linked lists merge. If so, where?

后端 未结 26 1427
陌清茗
陌清茗 2020-12-07 06:43

This question may be old, but I couldn\'t think of an answer.

Say, there are two lists of different lengths, merging at a point; how do we know wher

26条回答
  •  清歌不尽
    2020-12-07 07:17

    Use Map or Dictionary to store the addressess vs value of node. if the address alread exists in the Map/Dictionary then the value of the key is the answer. I did this:

    int FindMergeNode(Node headA, Node headB) {
    
    Map map = new HashMap();
    
    while(headA != null || headB != null)
    {
        if(headA != null && map.containsKey(headA.next))
        {
            return map.get(headA.next);
        }
    
        if(headA != null && headA.next != null)
        {
             map.put(headA.next, headA.next.data);
             headA = headA.next;
        }
    
        if(headB != null && map.containsKey(headB.next))
        {
            return map.get(headB.next);
        }
    
        if(headB != null && headB.next != null)
        {
            map.put(headB.next, headB.next.data);
            headB = headB.next;
        }
    }
    
    return 0;
    }
    

提交回复
热议问题