1 题目描述
2 算法思路
思路:
- 用两个指针A,B分别指向两个链表的头,然后以相同的速度遍历,如果指针到了末尾,就从对方的头再来
- 由题目可知,链表不存在循环,因此只要存在交点,就一定可以通过这种追赶的方式找到。
- 两个链表长度分别为L1+C、L2+C, C为公共部分的长度,按照楼主的做法: 第一个人走了L1+C步后,回到第二个人起点走L2步;第2个人走了L2+C步后,回到第一个人起点走L1步。 当两个人走的步数都为L1+L2+C时就两个家伙就相爱了
- 如果不存在,那么最后,node1 == node2 == null,循环会跳出
3 代码
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null) return null;
ListNode node1 = headA;
ListNode node2 = headB;
while(node1 != node2){
node1 = node1 == null ? headB : node1.next;
node2 = node2 == null ? headA : node2.next;
}
return node1;
}
}