【leetcode】环形链表✚环形链表II

大家好,我是苏貝,本篇博客带大家刷题,如果你觉得我写的还不错的话,可以给我一个赞👍吗,感谢❤️


目录

1.环形链表

点击查看题目

解题

思路:

c 复制代码
bool hasCycle(struct ListNode *head) {
    struct ListNode *slow=head;
    struct ListNode *fast=head;
    while(fast&&fast->next)
    {
        slow=slow->next;
        fast=fast->next->next;

        if(fast==slow)
            return true;
    }
    return false;
}

拓展:

1

慢指针一次走2步,快指针一次走3步,可以解决上面的题目吗?

可以的,因为它们也只是相差了1步,证明同上

2

慢指针一次走1步,快指针一次走3步,走4步,...n步行吗?下面用慢指针一次走1步,快指针一次走3步来证明


2.环形链表II

点击查看题目

思路:

c 复制代码
struct ListNode *detectCycle(struct ListNode *head) {
    struct ListNode *slow=head;
    struct ListNode *fast=head;
    while(fast&&fast->next)
    {
        slow=slow->next;
        fast=fast->next->next;
        //1.找到相遇的节点
        if(slow==fast)
        {
            //让meet从相遇节点开始走
            struct ListNode *meet=slow;
            while(head!=meet)
            {
                head=head->next;
                meet=meet->next;
            }   
            return meet;
        }
    }
    return NULL;
}

好了,那么本篇博客就到此结束了,如果你觉得本篇博客对你有些帮助,可以给个大大的赞👍吗,感谢看到这里,我们下篇博客见❤️

相关推荐
中二骚年9 小时前
Windows 安全中心 / 防火墙故障,calc和Microsoft Store,终端(管理员)无法正常打开。 原因 + 修复方案
windows·安全·microsoft
万联WANFLOW10 小时前
CVE-2026-98432 等漏洞自查:AI 查出的 Linux、Windows 漏洞,运维怎么确认受不受影响
linux·运维·windows·网络安全
AlanAshley12 小时前
Windows 中导致延迟的软硬件及协议比重
windows
yuezhilangniao12 小时前
win10中文 以及 PowerShell 开发日常
windows·powershell
文丑颜不良啊1 天前
LeetCode1661~1680题目解析
java·leetcode
共享家95271 天前
408 操作系统第一章
服务器·数据库·windows
Sakura_j_h_1 天前
GitHub Actions 打包 Windows exe:中文编码与产物上传
windows·ci/cd·打包发布·github·pyinstaller·github actions
xixiaoyunya1 天前
搭一个浏览器即用的二进制文件分发点:目录规范与权限边界实践
网络·windows
麻瓜code1 天前
Spring AI 全模块 API 字典一览(1.1.0 版)
人工智能·windows·spring
zrc0070071 天前
steam无法登录 steam错误 登录时出现错误。请稍后再试。解决办法 steam无法登录解决办法 湖南地区steam DNS问题解决办法
windows·经验分享·游戏·缓存·游戏程序·创业创新·玩游戏