【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;
}

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

相关推荐
mask哥7 小时前
力扣算法java实现汇总整理(上)
java·算法·leetcode
流年如夢10 小时前
栈和列队(LeetCode)
数据结构·算法·leetcode·链表·职场和发展
Byron Loong13 小时前
【调试】Dump 文件分析的完整流程
windows
Geoking.14 小时前
VSCode 安装 Claude Code 插件 + ccswitch 配置 DeepSeek API 完整教程(Windows 新手向)
ide·windows·vscode
潘达斯奈基~15 小时前
Windows 下 Claude Code使用 Agent Teams 配置教程
windows
星星码️16 小时前
LeetCode刷题简单篇之反转字母
c++·算法·leetcode
YL2004042617 小时前
027合并两个有序链表
java·数据结构·算法·链表
炽烈小老头18 小时前
【每天学习一点算法 2026/05/10】合并K个排序链表
学习·算法·链表
happymaker062618 小时前
Spring框架学习日记——DAY02(依赖注入的方式)
windows
honder试试18 小时前
Elasticsearch(es)在Windows系统上的安装与部署(含Kibana)
windows·elasticsearch·jenkins