Skip to content

Commit ff61754

Browse files
committed
solved: 141
1 parent e455c1d commit ff61754

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

code/141.linked-list-cycle.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* val: number
5+
* next: ListNode | null
6+
* constructor(val?: number, next?: ListNode | null) {
7+
* this.val = (val===undefined ? 0 : val)
8+
* this.next = (next===undefined ? null : next)
9+
* }
10+
* }
11+
*/
12+
13+
function hasCycle(_head: ListNode | null): boolean {
14+
const prevVisited = new Set<ListNode>();
15+
16+
let head = _head;
17+
18+
while (head) {
19+
if (prevVisited.has(head)) {
20+
return true;
21+
}
22+
23+
prevVisited.add(head);
24+
head = head.next;
25+
}
26+
27+
return false;
28+
}

0 commit comments

Comments
 (0)