Skip to content

Commit b91f539

Browse files
committed
Update 160. 相交链表
1 parent 599e3b2 commit b91f539

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

algorithms/intersection-of-two-linked-lists.js

+34-7
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,44 @@
1313
* @return {ListNode}
1414
*/
1515
var getIntersectionNode = function (headA, headB) {
16+
// reference: https://programmercarl.com/%E9%9D%A2%E8%AF%95%E9%A2%9802.07.%E9%93%BE%E8%A1%A8%E7%9B%B8%E4%BA%A4.html#javascript
1617
if (!headA || !headB) {
1718
return null;
1819
}
20+
const getLength = (head) => {
21+
let count = 0;
22+
let curr = head;
23+
while (curr) {
24+
count++;
25+
curr = curr.next;
26+
}
27+
return count;
28+
};
29+
let aLen = getLength(headA);
30+
let bLen = getLength(headB);
31+
let diff = Math.abs(aLen - bLen);
1932

20-
let currA = headA;
21-
let currB = headB;
22-
23-
while (currA !== currB) {
24-
currA = currA ? currA.next : headB;
25-
currB = currB ? currB.next : headA;
33+
if (aLen < bLen) {
34+
[headA, headB] = [headB, headA];
35+
[aLen, bLen] = [bLen, aLen];
36+
}
37+
while (diff--) {
38+
headA = headA.next;
39+
}
40+
while (headA !== headB) {
41+
headA = headA.next;
42+
headB = headB.next;
2643
}
44+
return headA;
2745

28-
return currA;
46+
// if (!headA || !headB) {
47+
// return null;
48+
// }
49+
// let currA = headA;
50+
// let currB = headB;
51+
// while (currA !== currB) {
52+
// currA = currA ? currA.next : headB;
53+
// currB = currB ? currB.next : headA;
54+
// }
55+
// return currA;
2956
};

0 commit comments

Comments
 (0)