--- title: 141.环形链表 date: 2023-09-12T00:00:00.000Z author: KazooTTT tags: - 算法 - 链表 - leetcode platform: leetcode number: 141 leetcode-url: 'https://leetcode.cn/problems/linked-list-cycle/' toAstro: true slug: 141-ring-chained-tables description: >- 该内容描述了一个用于检测链表中是否存在环的算法。算法通过使用两个指针,一个慢指针和一个快指针,在链表中移动。如果链表中存在环,快指针最终会追上慢指针;否则,快指针会先到达链表的末尾。算法首先检查链表的头节点是否为空或其下一个节点是否为空,如果是,则返回false,表示没有环。然后,算法进入一个循环,每次循环中慢指针前进一步,快指针前进两步。如果快指针变为null或其下一个节点为null,则返回false,表示没有环。如果循环中快指针与慢指针相遇,则返回true,表示链表中存在环。 date_created: 2025-01-04T03:44:53.000Z date_modified: 2025-02-19T03:44:14.000Z --- # 141.环形链表 ```ts /* * @lc app=leetcode.cn id=141 lang=typescript * * [141] 环形链表 */ // @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 { if (head === null || head.next === null) return false let slow = head let fast = head.next while (slow !== fast) { if (fast === null || fast.next === null) return false slow = slow.next fast = fast.next.next } return true } // @lc code=end ``` ![Pasted image 20230913211049]()