今天给大家讲一下相链表及判断相交开始的节点
首先我们里说说思路
如图: 一个指针指向a的表头a1一个指针指向b的表头我们设指向a的为pointA 指向b的为pointB
1.我们让pointA和pointB一起走只要啊pointA!=pointB就一直走
2.当a走到头时我们改变让pointA指向b的表头同样当b走到头时让pointB指向a的表头
3.让pointA和pointB互换走时如果相交一定会有pointA=pointB,此时即pointA为相交节点否则走完a,b返回null
数据结构要画图再说一遍要画图大家走一下这个过程自然就明白了
上代码:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA==null||headB==null){
return null;
}
ListNode a=headA;//指向a的表头
ListNode b=headB;//指向b的表头
boolean isChangeA=false;//headA指向b表头标记量
boolean isChangeB=false;//headB指向a表头标记量
while(a!=b){//当 a!=b时一直循环
a=a.next;
b=b.next;
//如果两个标记量为true并且a和b都走到了尾部为null返回null
if(isChangeA&&isChangeB&&a==null&&b==null){
return null;
}
//指向b的表头
if(a==null){
a=headB;
isChangeA=true;
}
//指向b的表头
if(b==null){
b=headA;
isChangeB=true;
}
}
//如果出循环说明找到了返回a或b
return a;
}
}