Skip to content

Commit 99bd132

Browse files
committed
linked list cycle solution
1 parent 471cb16 commit 99bd132

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed

linked-list-cycle/hyer0705.ts

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
if (!head || !head.next) return false;
15+
16+
let slow = head;
17+
let fast = head;
18+
while (fast && fast.next) {
19+
slow = slow.next;
20+
fast = fast.next.next;
21+
if (slow === fast) return true;
22+
}
23+
24+
return false;
25+
}

0 commit comments

Comments
 (0)