File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
1
+ class ListNode {
2
+ val : number ;
3
+ next : ListNode | null ;
4
+ constructor ( val ?: number , next ?: ListNode | null ) {
5
+ this . val = val === undefined ? 0 : val ;
6
+ this . next = next === undefined ? null : next ;
7
+ }
8
+ }
9
+
10
+ /**
11
+ * https://leetcode.com/problems/linked-list-cycle
12
+ * T.C. O(n)
13
+ * S.C. O(n)
14
+ */
15
+ function hasCycle ( head : ListNode | null ) : boolean {
16
+ const SET = new Set < ListNode > ( ) ;
17
+ while ( head ) {
18
+ if ( SET . has ( head ) ) return true ;
19
+ SET . add ( head ) ;
20
+ head = head . next
21
+ }
22
+ return false ;
23
+ } ;
24
+
25
+ /**
26
+ * T.C. O(n)
27
+ * S.C. O(1)
28
+ */
29
+ function hasCycle ( head : ListNode | null ) : boolean {
30
+ let fast = head ;
31
+ let slow = head ;
32
+
33
+ while ( fast && fast . next ) {
34
+ fast = fast . next . next ;
35
+ slow = slow ! . next ;
36
+
37
+ if ( fast === slow ) {
38
+ return true ;
39
+ }
40
+ }
41
+ return false ;
42
+ } ;
You can’t perform that action at this time.
0 commit comments