forked from doocs/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution.js
46 lines (44 loc) · 812 Bytes
/
Solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
var getIntersectionNode2 = function (headA, headB) {
if (!headA || !headB) {
return null;
}
let q = headA,
p = headB;
let lengthA = 1;
let lengthB = 1;
while (q.next) {
q = q.next;
lengthA++;
}
while (p.next) {
p = p.next;
lengthB++;
}
if (q !== p) {
return null;
}
(q = headA), (p = headB);
if (lengthA > lengthB) {
for (let i = 0; i < lengthA - lengthB; i++) {
q = q.next;
}
} else {
for (let i = 0; i < lengthB - lengthA; i++) {
p = p.next;
}
}
while (q !== p && q !== null) {
q = q.next;
p = p.next;
}
return q;
};
var getIntersectionNode = function (headA, headB) {
let p1 = headA;
let p2 = headB;
while (p1 != p2) {
p1 = p1 ? p1.next : headB;
p2 = p2 ? p2.next : headA;
}
return p1;
};