/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
int counta =0,countb=0;
ListNode preA = headA,preB = headB;
int length = 0;
while(headA != null){
counta++;
headA = headA.next;
}
while(headB != null){
countb++;
headB = headB.next;
}
if(countb - counta>0){
while(countb-counta-length!=0){
preB = preB.next;
length++;
}
}else{
while(counta-countb-length!=0){
preA = preA.next;
length++;
}
}
while(preA !=null && preB!= null){
if(preA == preB){
return preA;
}else{
preA = preA.next;
preB =preB.next;
}
}
return null;
}
}
先计算两个链表的长度,让长的链表先走长度之差,然后两个链表的指针开始一起走,如果中间有两个节点相同,直接返回,如果遍历到最后一个也没有,返回null