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

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

    There is no need to modify any list. There is a solution in which we only have to traverse each list once.

    1. Create two stacks, lets say stck1 and stck2.
    2. Traverse 1st list and push a copy of each node you traverse in stck1.
    3. Same as step two but this time traverse 2nd list and push the copy of nodes in stck2.
    4. Now, pop from both stacks and check whether the two nodes are equal, if yes then keep a reference to them. If no, then previous nodes which were equal are actually the merge point we were looking for.

提交回复
热议问题