给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。 图示两个链表在节点 c1 开始相交:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode tempA=headA;
ListNode tempB=headB;
while(tempA!=tempB){
//如果他两个相交
if(tempA==tempB){
return tempA;
}
//不想交 继续遍历 空的的去另一个里面遍历
tempA=(tempA==null?headB: tempA.next);
tempB=(tempB==null?headA: tempB.next);
}
//退出循环 说明他两个相等 都为null 或者为一个具体的值
return tempA;
}
}