21.1k views
5 votes
Write a program to find the node at which the intersection of two singly linked lists begins.

For example, the following two linked lists:
A: a1 → a2

c1 → c2 → c3

B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
If the two linked lists have no intersection at all, return null.
The linked lists must retain their original structure after the function returns.You may assume there are no cycles anywhere in the entire linked structure.Your code should preferably run in O(n) time and use only O(1) memory.

User Eyn
by
7.0k points

1 Answer

4 votes

Final answer:

To find the node at which the intersection of two singly linked lists begins, we can use the 'two-pointer' technique.

Step-by-step explanation:

To find the node at which the intersection of two singly linked lists begins, we can use the 'two-pointer' technique. We can initialize two pointers, one for each linked list, and traverse both lists until they intersect at a common node. The idea is to have one pointer start at the head of the first list and the other pointer start at the head of the second list. If a pointer reaches the end of a list, it is moved to the head of the other list. Eventually, the two pointers will meet at the intersection node, or they will reach the end of both lists indicating that there is no intersection.

Here is an example of how the code can be implemented in Python:

  1. Initialize two pointers, ptr1 and ptr2, pointing to the heads of the two linked lists.
  2. Traverse both lists simultaneously until they intersect or reach the end of both lists.
  3. If the pointers intersect, return the intersecting node.
  4. If the pointers reach the end of both lists, return null to indicate no intersection.
User Tim Jarvis
by
7.9k points