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

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

    Pavel's answer requires modification of the lists as well as iterating each list twice.

    Here's a solution that only requires iterating each list twice (the first time to calculate their length; if the length is given you only need to iterate once).

    The idea is to ignore the starting entries of the longer list (merge point can't be there), so that the two pointers are an equal distance from the end of the list. Then move them forwards until they merge.

    lenA = count(listA) //iterates list A
    lenB = count(listB) //iterates list B
    
    ptrA = listA
    ptrB = listB
    
    //now we adjust either ptrA or ptrB so that they are equally far from the end
    while(lenA > lenB):
        ptrA = ptrA->next
        lenA--
    while(lenB > lenA):
        prtB = ptrB->next
        lenB--
    
    while(ptrA != NULL):
        if (ptrA == ptrB):
            return ptrA //found merge point
        ptrA = ptrA->next
        ptrB = ptrB->next
    

    This is asymptotically the same (linear time) as my other answer but probably has smaller constants, so is probably faster. But I think my other answer is cooler.

提交回复
热议问题