LeetCode 面试题 02.08. 环路检测

文章目录

一、题目

给定一个链表,如果它是有环链表,实现一个算法返回环路的开头节点。若环不存在,请返回 null

如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达,则链表中存在环。 为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。注意:pos 不作为参数进行传递,仅仅是为了标识链表的实际情况。

点击此处跳转题目

示例 1:

输入:head = [3,2,0,-4], pos = 1

输出:tail connects to node index 1

解释:链表中有一个环,其尾部连接到第二个节点。

示例 2:

输入:head = [1,2], pos = 0

输出:tail connects to node index 0

解释:链表中有一个环,其尾部连接到第一个节点。

示例 3:

输入:head = [1], pos = -1

输出:no cycle

解释:链表中没有环。

进阶:

  • 你是否可以不用额外空间解决此题?

二、C# 题解

使用快慢指针 p、q 依次遍历,可以证明,当快慢指针相交时,此时慢指针 p 和头指针 head 前进相交处即为环路开头节点:

csharp 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     public int val;
 *     public ListNode next;
 *     public ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode DetectCycle(ListNode head) {
        if (head == null) return null;
        ListNode p = head, q = p;

        //  快慢指针相交
        do {
            if (p != null) p = p.next;
            if (q != null) q = q.next;
            if (q != null) q = q.next;
        } while (p != q);

        if (p == null) return null; // 检查空

        // 寻找环路开头节点
        while (p != head) {
            p = p.next;
            head = head.next;
        }

        return p;
    }
}
  • 时间复杂度: O ( n ) O(n) O(n)。
  • 空间复杂度: O ( 1 ) O(1) O(1)。
相关推荐
MobotStone33 分钟前
从金鱼记忆到过目不忘:Transformer 如何让AI真正理解一句话?
算法
炽烈小老头2 小时前
【每天学习一点算法 2025/12/19】二叉树的层序遍历
数据结构·学习·算法
Xの哲學2 小时前
Linux grep命令:文本搜索的艺术与科学
linux·服务器·算法·架构·边缘计算
soft20015252 小时前
MySQL Buffer Pool深度解析:LRU算法的完美与缺陷
数据库·mysql·算法
WBluuue3 小时前
AtCoder Beginner Contest 436(ABCDEF)
c++·算法
wearegogog1233 小时前
基于C# WinForm实现的带条码打印的固定资产管理
开发语言·c#
fie88893 小时前
广义 S 变换(GST)地震信号时频谱
算法
json{shen:"jing"}4 小时前
1-C语言的数据类型
c语言·c++·算法
im_AMBER4 小时前
数据结构 13 图 | 哈希表 | 树
数据结构·笔记·学习·算法·散列表
LYFlied4 小时前
【算法解题模板】动态规划:从暴力递归到优雅状态转移的进阶之路
数据结构·算法·leetcode·面试·动态规划