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

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

    Well, if you know that they will merge:

    Say you start with:

    A-->B-->C
            |
            V
    1-->2-->3-->4-->5
    

    1) Go through the first list setting each next pointer to NULL.

    Now you have:

    A   B   C
    
    1-->2-->3   4   5
    

    2) Now go through the second list and wait until you see a NULL, that is your merge point.

    If you can't be sure that they merge you can use a sentinel value for the pointer value, but that isn't as elegant.

提交回复
热议问题