File tree 1 file changed +34
-7
lines changed
1 file changed +34
-7
lines changed Original file line number Diff line number Diff line change 13
13
* @return {ListNode }
14
14
*/
15
15
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
16
17
if ( ! headA || ! headB ) {
17
18
return null ;
18
19
}
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 ) ;
19
32
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 ;
26
43
}
44
+ return headA ;
27
45
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;
29
56
} ;
You can’t perform that action at this time.
0 commit comments