/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
/**
* @param headA: the first list
* @param headB: the second list
* @return: a ListNode
*/
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
// Write your code here
if(headA==null||headB==null){
return null;
}
ListNode A=headA;
ListNode B=headB;
int A_length=1;
while(A.next!=null){
A=A.next;
A_length++;
}
int B_length=1;
while(B.next!=null){
B=B.next;
B_length++;
}
if(A!=B){
return null;
}
ListNode short_list=headA;
ListNode long_list=headB;
if(A_length>B_length){
long_list=headA;
short_list=headB;
}
for(int i=0;i<Math.abs(A_length-B_length);i++){
long_list=long_list.next;
}
while(long_list!=null){
if(long_list==short_list){
return long_list;
}else{
long_list=long_list.next;
short_list=short_list.next;
}
}
return null;
}
}