File tree Expand file tree Collapse file tree 1 file changed +52
-0
lines changed Expand file tree Collapse file tree 1 file changed +52
-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
+ // TC: O(n)
11
+ // SC: O(1)
12
+ function hasCycle ( head : ListNode | null ) : boolean {
13
+
14
+ let fast : ListNode | null = head ;
15
+ let slow : ListNode | null = head ;
16
+
17
+ while ( fast && fast . next ) {
18
+ fast = fast . next . next ;
19
+
20
+ if ( slow !== null ) {
21
+ slow = slow . next ;
22
+ } else {
23
+ return false ;
24
+ }
25
+
26
+ if ( fast === slow ) return true ;
27
+ }
28
+
29
+ return false ;
30
+ }
31
+
32
+
33
+ // TC: O(n)
34
+ // SC: O(n)
35
+ /*
36
+ function hasCycle(head: ListNode | null): boolean {
37
+
38
+ let dummy: ListNode | null = head;
39
+ const visited = new Set<ListNode>();
40
+
41
+ while (dummy) {
42
+ if (visited.has(dummy)) return true;
43
+
44
+ visited.add(dummy);
45
+
46
+ dummy = dummy.next;
47
+ }
48
+
49
+ return false;
50
+ }
51
+ */
52
+
You can’t perform that action at this time.
0 commit comments