https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
点击查看【bilibili】

题目

编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表
160. [简单]相交链表 Intersection of Two Linked Lists - 图1
在节点 c1 开始相交。

注意:

如果两个链表没有交点,返回 null.
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。

示例

160. [简单]相交链表 Intersection of Two Linked Lists - 图2

  1. 输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3
  2. 输出:Reference of the node with value = 8
  3. 输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。
  4. 从各自的表头开始算起,链表 A [4,1,8,4,5],链表 B [5,0,1,8,4,5]。
  5. A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。

160. [简单]相交链表 Intersection of Two Linked Lists - 图3

  1. 输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1
  2. 输出:Reference of the node with value = 2
  3. 输入解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。
  4. 从各自的表头开始算起,链表 A [0,9,1,2,4],链表 B [3,2,4]。
  5. A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。

解答

image.png
n1走完a1->c2,如果没有交点,走b1->c2,
n2走完b1->c2,然后走a1->c2
两者走的路程是相等的,这其中必有交点

答案

  1. var getIntersectionNode = function(headA, headB) {
  2. let n1 = headA
  3. let n2 = headB
  4. while(n1 != n2) {
  5. if(n1 === null) {
  6. n1 = headB
  7. }else {
  8. n1 = n1.next
  9. }
  10. if(n2 === null) {
  11. n2 = headA
  12. }else {
  13. n2 = n2.next
  14. }
  15. }
  16. return n1
  17. };