【LeetCode 面试经典150题】141. Linked List Cycle 环形链表

本文介绍如何使用快慢指针的方法判断给定链表`head`是否存在环。慢指针每次移动一个节点,快指针每次移动两个,若快慢指针相遇则有环,否则无环。这种方法可以在O(1)内存下解决该问题。
摘要由CSDN通过智能技术生成

141. Linked List Cycle

题目大意

Given head, the head of a linked list, determine if the linked list has a cycle in it.

There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail’s next pointer is connected to. Note that pos is not passed as a parameter.

Return true if there is a cycle in the linked list. Otherwise, return false.

中文释义

给定 head,一个链表的头节点,判断这个链表是否有环。

如果链表中有一些节点可以通过不断跟随 next 指针再次到达,则链表中存在环。在内部,pos 用于表示尾节点的 next 指针连接到的节点的索引。注意 pos 不作为参数传递。

如果链表中存在环,则返回 true。否则,返回 false

示例

Example 1:
在这里插入图片描述

Input: head = [3,2,0,-4], pos = 1
Output: true
Explanation: 链表中存在一个环,其中尾部连接到第 1 个节点(0 索引)。

Example 2:
在这里插入图片描述

Input: head = [1,2], pos = 0
Output: true
Explanation: 链表中存在一个环,其中尾部连接到第 0 个节点。

Example 3:
在这里插入图片描述

Input: head = [1], pos = -1
Output: false
Explanation: 链表中不存在环。

限制条件

  • 链表中节点的数目范围是 [0, 104]。
  • -105 <= Node.val <= 105
  • pos 为 -1 或者链表中的一个有效索引。

进阶问题

你能否使用 O(1)(即常数)内存解决此问题?

解题思路

方法

即判断给定的链表 head 是否含有环。这种方法使用快慢指针的技巧,其中慢指针每次移动一个节点,快指针每次移动两个节点。

  1. 初始化快慢指针

    • 创建两个指针 slowfast,都初始化为指向头节点 head
  2. 遍历链表

    • 使用一个循环来移动快慢指针,直到 fast 或者 fast->nextnullptr(这表示到达链表末尾,没有环):
      • 慢指针 slow 每次向前移动一个节点。
      • 快指针 fast 每次向前移动两个节点。
      • 如果快慢指针相遇(即 slow == fast),则表示链表中有环,返回 true
  3. 检测环

    • 如果快指针到达链表末尾(即 fastnullptrfast->nextnullptr),则表示链表中没有环,返回 false

代码

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) {
                return true;  // 发现环
            }
        }
        return false;  // 链表没有环
    }
};
  • 8
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值