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

后端 未结 26 1428
陌清茗
陌清茗 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:22

    Step 1: find lenght of both the list Step 2 : Find the diff and move the biggest list with the difference Step 3 : Now both list will be in similar position. Step 4 : Iterate through list to find the merge point

    //Psuedocode
    def findmergepoint(list1, list2):
    lendiff = list1.length() > list2.length() : list1.length() - list2.length() ? list2.lenght()-list1.lenght()
    biggerlist = list1.length() > list2.length() : list1 ? list2  # list with biggest length
    smallerlist = list1.length() < list2.length() : list2 ? list1 # list with smallest length
    
    
    # move the biggest length to the diff position to level both the list at the same position
    for i in range(0,lendiff-1):
        biggerlist = biggerlist.next
    #Looped only once.  
    while ( biggerlist is not None and smallerlist is not None ):
        if biggerlist == smallerlist :
            return biggerlist #point of intersection
    
    
    return None // No intersection found
    

提交回复
热议问题