File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Expand file tree Collapse file tree 1 file changed +38
-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+ // @leet start
10+ /**
11+ * Definition for singly-linked list.
12+ * class ListNode {
13+ * val: number
14+ * next: ListNode | null
15+ * constructor(val?: number, next?: ListNode | null) {
16+ * this.val = (val===undefined ? 0 : val)
17+ * this.next = (next===undefined ? null : next)
18+ * }
19+ * }
20+ */
21+
22+ function detectCycle ( _head : ListNode | null ) : ListNode | null {
23+ const prevVisited = new Set < ListNode > ( ) ;
24+
25+ let head = _head ;
26+
27+ while ( head ) {
28+ if ( prevVisited . has ( head ) ) {
29+ return head ;
30+ }
31+
32+ prevVisited . add ( head ) ;
33+ head = head . next ;
34+ }
35+
36+ return null ;
37+ } ;
38+ // @leet end
You can’t perform that action at this time.
0 commit comments