File tree 2 files changed +69
-0
lines changed
0160.Intersection of Two Linked Lists
2 files changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ var hasCycle2 = function ( head ) {
2
+ let slow = head
3
+ let fast = head
4
+ while ( fast !== null && fast . next !== null ) {
5
+ slow = slow . next
6
+ fast = fast . next . next
7
+ if ( slow === fast ) {
8
+ return true
9
+ }
10
+ }
11
+ return false
12
+ }
13
+
14
+ var hasCycle3 = function ( head ) {
15
+ let arr = [ ]
16
+ while ( head !== null ) {
17
+ if ( arr . includes ( head ) ) {
18
+ return true
19
+ }
20
+ arr . push ( head )
21
+ head = head . next
22
+ }
23
+ return false
24
+ }
Original file line number Diff line number Diff line change
1
+ var getIntersectionNode2 = function ( headA , headB ) {
2
+ if ( ! headA || ! headB ) {
3
+ return null
4
+ }
5
+ let q = headA , p = headB
6
+ let lengthA = 1
7
+ let lengthB = 1
8
+ while ( q . next ) {
9
+ q = q . next
10
+ lengthA ++
11
+ }
12
+ while ( p . next ) {
13
+ p = p . next
14
+ lengthB ++
15
+ }
16
+ if ( q !== p ) {
17
+ return null
18
+ }
19
+
20
+ q = headA , p = headB
21
+ if ( lengthA > lengthB ) {
22
+ for ( let i = 0 ; i < lengthA - lengthB ; i ++ ) {
23
+ q = q . next
24
+ }
25
+ } else {
26
+ for ( let i = 0 ; i < lengthB - lengthA ; i ++ ) {
27
+ p = p . next
28
+ }
29
+ }
30
+ while ( q !== p && q !== null ) {
31
+ q = q . next
32
+ p = p . next
33
+ }
34
+ return q
35
+ } ;
36
+
37
+ var getIntersectionNode = function ( headA , headB ) {
38
+ let p1 = headA ;
39
+ let p2 = headB ;
40
+ while ( p1 != p2 ) {
41
+ p1 = p1 ? p1 . next : headB ;
42
+ p2 = p2 ? p2 . next : headA ;
43
+ }
44
+ return p1 ;
45
+ }
You can’t perform that action at this time.
0 commit comments