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

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

    If

    • by "modification is not allowed" it was meant "you may change but in the end they should be restored", and
    • we could iterate the lists exactly twice

    the following algorithm would be the solution.

    First, the numbers. Assume the first list is of length a+c and the second one is of length b+c, where c is the length of their common "tail" (after the mergepoint). Let's denote them as follows:

    x = a+c
    y = b+c
    

    Since we don't know the length, we will calculate x and y without additional iterations; you'll see how.

    Then, we iterate each list and reverse them while iterating! If both iterators reach the merge point at the same time, then we find it out by mere comparing. Otherwise, one pointer will reach the merge point before the other one.

    After that, when the other iterator reaches the merge point, it won't proceed to the common tail. Instead will go back to the former beginning of the list that had reached merge-point before! So, before it reaches the end of the changed list (i.e. the former beginning of the other list), he will make a+b+1 iterations total. Let's call it z+1.

    The pointer that reached the merge-point first, will keep iterating, until reaches the end of the list. The number of iterations it made should be calculated and is equal to x.

    Then, this pointer iterates back and reverses the lists again. But now it won't go back to the beginning of the list it originally started from! Instead, it will go to the beginning of the other list! The number of iterations it made should be calculated and equal to y.

    So we know the following numbers:

    x = a+c
    y = b+c
    z = a+b
    

    From which we determine that

    a = (+x-y+z)/2
    b = (-x+y+z)/2
    c = (+x+y-z)/2
    

    Which solves the problem.

提交回复
热议问题