链表相交
链表相交
/**
* 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,LenB=0;
ListNode curA=headA;
ListNode curB=headB;
//计算两个链表的长度
while(curA!=null){
lenA++;
curA=curA.next;
}
while(curB!=null){
LenB++;
curB=curB.next;
}
curA=headA;
curB=headB;
//统一规则,链表A较长
if(LenB>lenA){
int teamLen=lenA;
lenA=LenB;
LenB=teamLen;
ListNode team=curA;
curA=curB;
curB=team;
}
//计算差值
int gap=lenA-LenB;
//对应末尾
while(gap-->0){
curA=curA.next;
}
//遍历连个链表,相同结点就返回该节点
while(curA!=null){
if(curA==curB){
return curA;
}
curA=curA.next;
curB=curB.next;
}
return null;
}
}