Q15 Intersection of Two Linked Lists - LeetCode
Tue Jan 17 2023 05:18:51 GMT+0000 (Coordinated Universal Time)
Saved by
@Ayush_dabas07
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public int length (ListNode head ){
ListNode curr = head;
int count = 0;
while(curr!=null){
count++;
curr = curr.next;
}
return count;
}
public ListNode answer(ListNode headA, ListNode headB,int diff) {
ListNode curr1 = headA;
ListNode curr2 = headB;
while(diff > 0){
curr1 = curr1.next;
diff--;
}
while(curr1 != null){
if(curr1 == curr2)
return curr1;
curr1 = curr1.next;
curr2 = curr2.next;
}
return null;
}
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null)
return null;
//find length of LL
int len1 = length(headA);
int len2 = length(headB);
int diff = 0;
//then find difference
diff = Math.max(len1,len2) - Math.min(len1,len2);
//skip no. of diff nodes from larger LL and start comparing one by one
if(len1 >= len2)
return answer( headA, headB,diff);
else
return answer( headB , headA,diff);
}
}
content_copyCOPY
https://leetcode.com/problems/intersection-of-two-linked-lists/
Comments