/**
* 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);
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter