From a114d3b2497d9776e8b9621d6b9df386b6eda8e7 Mon Sep 17 00:00:00 2001 From: Neha Gupta <78951376+Neha611@users.noreply.github.com> Date: Tue, 5 Mar 2024 20:11:45 +0530 Subject: [PATCH] Create Intersection of Two Linked Lists This is Leetcode Easy problem in which we have to find Intersection of two Linked Lists and return it . I have provided code for this problem with explanation. --- .../Intersection of Two Linked Lists | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) create mode 100644 Data-Structures/Linked-List/Intersection of Two Linked Lists diff --git a/Data-Structures/Linked-List/Intersection of Two Linked Lists b/Data-Structures/Linked-List/Intersection of Two Linked Lists new file mode 100644 index 0000000000..bbef1bae6b --- /dev/null +++ b/Data-Structures/Linked-List/Intersection of Two Linked Lists @@ -0,0 +1,36 @@ +/** + * A LinkedList based solution for Intersection of Two Linked Lists + * + */ +import { Node } from './SinglyLinkedList.js'; + +/* +Problem Statement: +Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null. + +Link for the Problem: https://leetcode.com/problems/intersection-of-two-linked-lists/description/ +*/ + +class getIntersectionNode{ + + solution(head1,head2){ + let t1=head1; /*reference to list 1*/ + let t2=head2; /*reference to list 2*/ + if(t1==null||t2==null) + { + return null; + } + /* checking till we get same nodes in list1 and list2 */ + while(t1!=t2){ + t1=t1.next; + t2=t2.next; + if(t1==t2) + return t1; + if(t1==null) + t1=head2; + if(t2==null) + t2=head1; + } + return t1; + } +}