https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
点击查看【bilibili】
题目
编写一个程序,找到两个单链表相交的起始节点。
如下面的两个链表:![160. [简单]相交链表 Intersection of Two Linked Lists - 图1](/uploads/projects/ynzy@rtlpm4/1b6028be7320b0b65a90a9a9564380bb.png)
在节点 c1 开始相交。
注意:
如果两个链表没有交点,返回 null.
在返回结果后,两个链表仍须保持原有的结构。
可假定整个链表结构中没有循环。
程序尽量满足 O(n) 时间复杂度,且仅用 O(1) 内存。
示例
![160. [简单]相交链表 Intersection of Two Linked Lists - 图2](/uploads/projects/ynzy@rtlpm4/d75bbb771391e707c96789bf8c88b3c9.png)
输入:intersectVal = 8, listA = [4,1,8,4,5], listB = [5,0,1,8,4,5], skipA = 2, skipB = 3输出:Reference of the node with value = 8输入解释:相交节点的值为 8 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [4,1,8,4,5],链表 B 为 [5,0,1,8,4,5]。在 A 中,相交节点前有 2 个节点;在 B 中,相交节点前有 3 个节点。
![160. [简单]相交链表 Intersection of Two Linked Lists - 图3](/uploads/projects/ynzy@rtlpm4/482410bff15d21194dac1ec761a5a1cf.png)
输入:intersectVal = 2, listA = [0,9,1,2,4], listB = [3,2,4], skipA = 3, skipB = 1输出:Reference of the node with value = 2输入解释:相交节点的值为 2 (注意,如果两个链表相交则不能为 0)。从各自的表头开始算起,链表 A 为 [0,9,1,2,4],链表 B 为 [3,2,4]。在 A 中,相交节点前有 3 个节点;在 B 中,相交节点前有 1 个节点。
解答

n1走完a1->c2,如果没有交点,走b1->c2,
n2走完b1->c2,然后走a1->c2
两者走的路程是相等的,这其中必有交点
答案
var getIntersectionNode = function(headA, headB) {let n1 = headAlet n2 = headBwhile(n1 != n2) {if(n1 === null) {n1 = headB}else {n1 = n1.next}if(n2 === null) {n2 = headA}else {n2 = n2.next}}return n1};
