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

后端 未结 26 1439
陌清茗
陌清茗 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-07 07:16

    If we could iterate lists exactly twice, than I can provide method for determining merge point:

    • iterate both lists and calculate lengths A and B
    • calculate difference of lengths C = |A-B|;
    • start iterating both list simultaneously, but make additional C steps on list which was greater
    • this two pointers will meet each other in the merging point

提交回复
热议问题