/**
* 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 lenA = 0;
int lenB = 0;
ListNode curA = headA;
ListNode curB = headB;
//获取链表A的长度
while(curA!=null){
lenA++;
curA=curA.next;
}
//获取链表B的长度
while(curB!=null){
lenB++;
curB=curB.next;
}
curA = headA;
curB = headB;
//让curA为最长链表的头,lenA为其长度
if(lenA<lenB){
//swap(lenA,lenB);
int temp=lenA;
lenA=lenB;
lenB=temp;
//swap(curA,curB);
ListNode tempNode = curA;
curA=curB;
curB=tempNode;
}
//求出两个链表长度的差值
int gap = lenA-lenB;
//让长的链表与端的链表尾部对齐
while(gap-- >0){
curA = curA.next;
}
//比较curA和curB是否相同
while(curA!=null){
if(curA == curB){ //相同就结束返回
return curA;
}
//不相同,同时向后移动curA和curB
curA=curA.next;
curB=curB.next;
}
return null;
}
}