How to find intersection of two LinkedList in java ?

By | June 22, 2020

In this post, we will talk and learn How to find Intersection of two linked lists.

Let’s say there are two singly LinkedList’s because of some programming error, the end node of one of the LinkedList got linked to the second LinkedList and formed a Y shaped list. We have to write a program to get the point where these two LinkedList’s merge

For example, the following two linked lists:

This diagram shows an example with two linked lists having 30 as intersection points.

The Logic used in this Program:

Here is the very simple Logic to find Intersection of two linked lists.

  • First of all, find the length of both singly-linked lists.
  • Afterward, we find the bigger linked list and iterate up to the difference between two linked lists.
  • You should note that two linked lists will become equal at this step.
  • Iterate over both the linked lists and keep checking if there is any common node present if we find one then return that Node else return null

Below is the complete source code:

Output of this Program:

First LinkedList::
10 20 30 40 50
Second LinkedList::
25 30 40 50
Intersecting node is: 30

You May Also Like:

That’s all about How to find the intersection of two LinkedList in java?
If you have any feedback or suggestion please feel free to drop in below comment box.

Leave a Reply

Your email address will not be published. Required fields are marked *