相交链表(判断两个链表是否相交并且求出交点)
思路:
1.先定义两个引用A,B和两个计数器,在分别遍历AB两个链表并且记录节点个数后,把A,B两个链表重新指向表头
2.判断出长链表是哪个,然后让长链表先走两个链表的差值步
3.然后A,B两个链表同时走,相等时,就是交点处节点
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//AB链表为空
if(headA == null || headB == null){
return null;
}
//遍历A B链表 并分别记录节点个数
int countlistA = 0;
int countlistB = 0;
ListNode listA = headA;
ListNode listB = headB;
while(null != listA){
countlistA++;
listA = listA.next;
}
while(null != listB){
countlistB++;
listB = listB.next;
}
if(listA != listB){
return null;
}
//A B再次指向头节点
listA = headA;
listB = headB;
//判断节点大小 让长节点的先走 两个节点的差值步
int gap = countlistA - countlistB;
if(gap > 0){
while( 0 != gap--){
listA = listA.next;
}
}else{
while(0 != gap++){
listB = listB.next;
}
}
//然后遍历A B链表 相等时就是相交的节点位置
while(listA != listB){
listA = listA.next;
listB = listB.next;
}
return listA;
}
}
运行结果
本文含有隐藏内容,请 开通VIP 后查看