题目:
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
示例:
-
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
-
输出:Intersected at ‘8’
-
解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。
在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
来源:力扣(LeetCode)
-
输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
-
输出:Intersected at ‘2’
-
解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。
从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。
在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
来源:力扣(LeetCode)
代码实现:
public class LC0207 {
}
class Solution5 {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//A:3->2->4
//B:0->9->1->2->4
//A指针指向A的头节点
ListNode currentA = headA;
//B指针指向B的头节点
ListNode currentB = headB;
//求出A链表的长度
int lengthA = 0;
while (currentA != null) {
lengthA++;
currentA = currentA.next;
}
//求出B链表的长度
int lengthB = 0;
while (currentB != null) {
lengthB++;
currentB = currentB.next;
}
//让两个指针重新指向各自头结点
currentA = headA;
currentB = headB;
//让A永远是更长的那个链表的指针
//可以不再分情况编写代码,减少重复代码
if (lengthB > lengthA) {
//存储临时变量
int temp = lengthA;
lengthA = lengthB;
lengthB = temp;
//存储临时链表
ListNode tempNode = currentA;
currentA = currentB;
currentB = tempNode;
}
//代码到这里,A链表就永远是更长的那个链表,统一处理
//A:0->9->1->2->4
//B:3->2->4
//求长度差
int gap = lengthA - lengthB;
//滑动A的指针,让A和B的指针处在同一位置
while (gap-- > 0) {
currentA = currentA.next;
}
//此时A和B的指针处在同一位置
//A:1->2->4
//B:3->2->4
//找出A和B相同节点
while (currentA != null) {
if (currentA == currentB) {
return currentA;
}
currentA = currentA.next;
currentB = currentB.next;
}
//代码到这里,证明没有相同交点
return null;
}
}