141. Linked List Cycle
June 24, 2025
04:32 AM
No headings found
Loading content...
No headings found
Problem
Bài toán yêu cầu kiểm tra xem trong một linked list có tồn tại cycle hay không, tức là một node nào đó trỏ ngược lại một node trước đó trong danh sách hay không
Approach
Solution
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
13function hasCycle(head: ListNode | null): boolean {
14 if(!head) return false;
15
16 let slow = head;
17 let fast = head;
18
19 while(fast && fast.next) {
20 slow = slow.next;
21 fast = fast.next.next;
22 if(slow === fast) return true;
23 }
24
25 return false
26};