141. Linked List Cycle
Tags:
Easy
Skills:
Linked List
June 24, 2025
04:32 AM
No headings found
Loading content...
Related Posts
Leetcode
No headings found
Related Posts
Leetcode
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};