mirror of
https://github.com/KazooTTT/kazoottt-blog-v2.git
synced 2025-06-22 10:11:29 +08:00
1.9 KiB
1.9 KiB
title, date, author, tags, platform, number, leetcode-url, toAstro, slug, description, date_created, date_modified
title | date | author | tags | platform | number | leetcode-url | toAstro | slug | description | date_created | date_modified | |||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
141.环形链表 | 2023-09-12T00:00:00.000Z | KazooTTT |
|
leetcode | 141 | https://leetcode.cn/problems/linked-list-cycle/ | true | 141-ring-chained-tables | 该内容描述了一个用于检测链表中是否存在环的算法。算法通过使用两个指针,一个慢指针和一个快指针,在链表中移动。如果链表中存在环,快指针最终会追上慢指针;否则,快指针会先到达链表的末尾。算法首先检查链表的头节点是否为空或其下一个节点是否为空,如果是,则返回false,表示没有环。然后,算法进入一个循环,每次循环中慢指针前进一步,快指针前进两步。如果快指针变为null或其下一个节点为null,则返回false,表示没有环。如果循环中快指针与慢指针相遇,则返回true,表示链表中存在环。 | 2025-01-04T03:44:53.000Z | 2025-02-19T03:44:14.000Z |
141.环形链表
/*
* @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