Files
kazoottt-blog-v2/src/content/note/141.环形链表.md
2025-02-19 17:30:11 +00:00

57 lines
1.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
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](<https://pictures.kazoottt.top/2024/10/20241017-4f53a7eae19ab17b762648f666cfabb6.png>)