求两个链表的交点。给个LC的截图作例子,

两种思路,一个是需要求出两个链表各自的长度,当两者不想等的时候,需要先遍历长的链表,使得其剩下的长度要跟短的链表长度相等,再去找两者的交点。如图所示就是需要先让B移动到node.value = 0的那个节点,再遍历A和B,看看交点在哪里。
时间O(n)
空间O(1)
1 /**
2 * @param {ListNode} headA
3 * @param {ListNode} headB
4 * @return {ListNode}
5 */
6 var getIntersectionNode = function(headA, headB) {
7 // corner case
8 if (headA === null || headB === null) {
9 return null;
10 }
11
12 // normal case
13 let lenA = len(headA);
14 let lenB = len(headB);
15 if (lenA > lenB) {
16 while (lenA !== lenB) {
17 headA = headA.next;
18 lenA--;
19 }
20 } else {
21 while (lenA !== lenB) {
22 headB = headB.next;
23 lenB--;
24 }
25 }
26 while (headA !== headB) {
27 headA = headA.next;
28 headB = headB.next;
29 }
30 return headA;
31 };
32
33 var len = function(head) {
34 let res = 1;
35 while (head !== null) {
36 res++;
37 head = head.next;
38 }
39 return res;
40 }
另外一种思路是不求两个链表的长度,分别遍历A和B。如果按照此例,遍历完A和B的时候并不能找到两者的交点,此时可以将A的末尾接上B(A+B),或者将B的末尾接上A(B+A),这样保证了两者遍历的长度相等,就一定能找到交点。这个例子给的不是特别好,因为遍历的时候,程序很可能在8之前的那个1的node就退出循环了。但是如果这个节点不想等,程序会在8的地方退出。
A: 4 - 1 - 8 - 4 - 5 - 5 - 0 - 1 - 8 - 4 - 5
B: 5 - 0 - 1 - 8 - 4 - 5 - 4 - 1 - 8 - 4 - 5
时间O(m + n), A和B的长度和
空间O(1)
1 /**
2 * @param {ListNode} headA
3 * @param {ListNode} headB
4 * @return {ListNode}
5 */
6 var getIntersectionNode = function(headA, headB) {
7 // corner case
8 if (headA === null || headB === null) {
9 return null;;
10 }
11
12 // normal case
13 let a = headA;
14 let b = headB;
15 while (a !== b) {
16 a = a === null ? headB : a.next;
17 b = b === null ? headA : b.next;
18 }
19 return a;
20 };