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

1.9 KiB
Raw Blame History

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
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

Pasted image 20230913211049