160. Intersection of Two Linked
2020-03-18 本文已影响0人
7ccc099f4608
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
![](https://img.haomeiwen.com/i1560080/3e2eea96d99e9674.png)
(图片来源https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
)
日期 | 是否一次通过 | comment |
---|---|---|
2020-03-18 | 0 | |
2020-03-18 | 0 |
public ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
//boundary check
if(headA == null || headB == null) {
return null;
}
ListNode a = headA, b = headB;
/**
*
* 1. 如果A/B长度相同,则能够同时遍历到交点;
* 2. 如果长度不同,则较短的链表先到终点null(假设为A),然后a赋值为较长的链表(假设为B)。
* 于是等较长的链表B到达终点时(b上的),a已经走过了A/B链表的长度差(len(B)-len(A))。
* 此时,把b赋值为A,二者同时从距离终点null等长的地方开始遍历,寻找交点。
* 如果两链表没有交点,则会死循环遍历下去
* */
while( a != b) {
//for the end of first iteration, we just reset the pointer to the head of another linkedlist
a = a == null ? headB : a.next;
b = b == null ? headA : b.next;
}
return a;
}