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