160.相交链表
/**
* 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) {
if(headA==null||headB==null){
return null;
}
ListNode curA = headA;
ListNode curB = headB;
//用来统计headA的链表长度
int lengthA = 1;
//用来统计headB的链表长度
int lengthB = 1;
while(curA!=null){
curA=curA.next;
lengthA++;
}
while(curB!=null){
curB=curB.next;
lengthB++;
}
//重新归零
curA=headA;
curB=headB;
//长度长的结点先走
if(lengthA>lengthB){
for(int i=0;i<lengthA-lengthB;i++){
curA=curA.next;
}
}else {
for(int i=0;i<lengthB-lengthA;i++){
curB=curB.next;
}
}
//判断是否有交点
while(curA!=null&&curB!=null){
if(curA==curB){//有交点
return curA;
}
curA=curA.next;
curB=curB.next;
}
//无交点
return null;
}
}