File tree Expand file tree Collapse file tree 1 file changed +90
-0
lines changed Expand file tree Collapse file tree 1 file changed +90
-0
lines changed Original file line number Diff line number Diff line change
1
+ /*
2
+ https://leetcode.com/problems/linked-list-cycle-ii/description/
3
+
4
+ Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
5
+
6
+ Note: Do not modify the linked list.
7
+
8
+ Follow up:
9
+ Can you solve it without using extra space?
10
+ */
11
+
12
+
13
+ // Optimal solution
14
+ /**
15
+ * @param {ListNode } head
16
+ * @return {ListNode }
17
+ */
18
+ var detectCycle = function ( head ) {
19
+ if ( head === null )
20
+ return null ;
21
+
22
+ var slow = head ;
23
+ var fast = head ;
24
+
25
+ while ( fast . next !== null && fast . next . next !== null ) {
26
+ slow = slow . next ;
27
+ fast = fast . next . next ;
28
+ if ( fast == slow ) {
29
+ var a = head ;
30
+ var b = slow ;
31
+ while ( a !== b ) {
32
+ a = a . next ;
33
+ b = b . next ;
34
+ }
35
+ return a ;
36
+ }
37
+ }
38
+ return null ;
39
+ } ;
40
+
41
+ // Naiver solution using a Set
42
+ var detectCycle2 = function ( head ) {
43
+ if ( head === null || head . next === null ) {
44
+ return null ;
45
+ }
46
+ var setNodes = new Set ( ) ;
47
+ var iter = head ;
48
+ while ( iter !== null ) {
49
+ if ( setNodes . has ( iter ) ) {
50
+ return iter ;
51
+ }
52
+ setNodes . add ( iter ) ;
53
+ iter = iter . next
54
+ }
55
+ return null ;
56
+ } ;
57
+
58
+ var main = function ( ) {
59
+ const head = buildCycle ( ) ;
60
+ console . log ( detectCycle ( head ) ) ;
61
+ }
62
+ main ( ) ;
63
+
64
+ function ListNode ( val ) {
65
+ this . val = val ;
66
+ this . next = null ;
67
+ }
68
+
69
+ function buildCycle ( ) {
70
+ var node1 = new ListNode ( 1 ) ;
71
+ var node2 = new ListNode ( 2 ) ;
72
+ var node3 = new ListNode ( 3 ) ;
73
+ var node4 = new ListNode ( 4 ) ;
74
+ var node5 = new ListNode ( 5 ) ;
75
+
76
+ node1 . next = node2 ;
77
+ node2 . next = node3 ;
78
+ node3 . next = node4 ;
79
+ node4 . next = node5 ;
80
+ node5 . next = node2 ;
81
+
82
+ /* 1 -> 2 -> 3 -> 4 -> 5
83
+ \ /
84
+ - - - - -
85
+ */
86
+ return node1 ;
87
+ }
88
+
89
+ main ( ) ;
90
+ module . exports . main = main ;
You can’t perform that action at this time.
0 commit comments