-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path141.linked-list-cycle.ts
More file actions
51 lines (43 loc) · 910 Bytes
/
Copy path141.linked-list-cycle.ts
File metadata and controls
51 lines (43 loc) · 910 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/*
* @lc app=leetcode id=141 lang=typescript
*
* [141] Linked List Cycle
*/
// @lc code=start
/**
* Definition for singly-linked list.
* class ListNode {
* val: number
* next: ListNode | null
* constructor(val?: number, next?: ListNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
* }
*/
// function hasCycle(head: ListNode | null): boolean {
// let cur = head
// const arr = [cur]
// while(cur?.next) {
// cur = cur.next
// if (arr.includes(cur)) {
// return true
// }
// arr.push(cur)
// }
// return false
// };
// use Set
function hasCycle(head: ListNode | null): boolean {
let cur = head
const arr = [cur]
while(cur?.next) {
cur = cur.next
if (arr.includes(cur)) {
return true
}
arr.push(cur)
}
return false
};
// @lc code=end