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

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

相关推荐
vfvfb5 小时前
bat批量去掉本文件夹中的文件扩展名
服务器·windows·批处理·删除扩展名·bat技巧
_Itachi__5 小时前
LeetCode 热题 100 74. 搜索二维矩阵
算法·leetcode·矩阵
chao_7896 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
编程绿豆侠9 小时前
力扣HOT100之多维动态规划:1143. 最长公共子序列
算法·leetcode·动态规划
笑口常开xpr11 小时前
数 据 结 构 进 阶:哨 兵 位 的 头 结 点 如 何 简 化 链 表 操 作
数据结构·链表·哨兵位的头节点
我命由我1234511 小时前
VSCode - VSCode 放大与缩小代码
前端·ide·windows·vscode·前端框架·编辑器·软件工具
PT_silver11 小时前
tryhackme——Abusing Windows Internals(进程注入)
windows·microsoft
爱炸薯条的小朋友12 小时前
C#由于获取WPF窗口名称造成的异常报错问题
windows·c#·wpf
Lw老王要学习13 小时前
VScode 使用 git 提交数据到指定库的完整指南
windows·git·vscode