Linked List Intersection Point


this is my code. I dont get it, what went wrong!

Hello @Kinjal,

You have missed an important part of the question:
If the linked lists are not intersecting at any point then print -1.
Example:
5
15 25 40 50
5
10 20 30 60 70

Hope, this would help.
Give a like if you are satisfied.

I included in the main().

Hello @S18ML0016,

After analyzing your code, i have found the following mistakes in it that is leading to errors:

  1. Incorrect formulation of linked list.
    Reason:
    You have not initialized next point to NULL.
    Thus, introducing an extra node.
    Suggestion:
    Try to print your lists for previously mentioned example.

  2. Your code will fail for two types of test cases:
    Example 1: when first node is the intersecting point
    4
    10 25 40 50
    4
    10 25 40 50
    Example 2: when there is no intersecting point
    4
    15 25 40 50
    5
    10 20 30 60 70

I have corrected your code:

Hope, this would help.
Give a like if you are satisfied.


So, i have not initialized next=NULL; but still passed all the test cases. So, I wanna know, why we will need to initialize next=NULL; ??

Hello @Kinjal,

The reason for suggesting that change is due to an observation made while I was debugging your code earlier:

  1. As you can see in the figure below that your code is inserting and extra node after the first node while building the list:

  2. The reason for that is the condition you have specified inside the while loop that iterates it to one location ahead which can be seen in the figure below:

  3. After initializing next=NULL, this problem has been resolved:

Hope, this would help.

1 Like

That’s a very good and profound description I’ve ever got. Now I got it. Thank you very much, brother.

Anytime @Kinjal,

Please, mark it as resolved.