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

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

相关推荐
界面开发小八哥29 分钟前
界面控件DevExpress WPF v25.1预览 - 支持Windows 11系统强调色
windows·wpf·界面控件·devexpress·ui开发·.net 9
Wendy_robot1 小时前
【滑动窗口+哈希表/数组记录】Leetcode 438. 找到字符串中所有字母异位词
c++·算法·leetcode
程序员-King.1 小时前
day49—双指针+贪心—验证回文串(LeetCode-680)
算法·leetcode·贪心算法·双指针
Y1nhl3 小时前
力扣hot100_链表(3)_python版本
python·算法·leetcode·链表·职场和发展
前端 贾公子3 小时前
详解 LeetCode 第 242 题 - 有效的字母组
算法·leetcode·职场和发展
岫珩4 小时前
“由于启动计算机时出现了页面文件配置问题,Windows在你的计算机上创建了一个临时页面文件。。。”的问题解决
windows
李菠菜5 小时前
解决Windows系统下Git克隆时报错“unable to checkout working tree”的方法详解
windows·git
Demons_kirit6 小时前
LeetCode 2799、2840题解
算法·leetcode·职场和发展
软行6 小时前
LeetCode 每日一题 2845. 统计趣味子数组的数目
数据结构·c++·算法·leetcode
雾月557 小时前
LeetCode 1292 元素和小于等于阈值的正方形的最大边长
java·数据结构·算法·leetcode·职场和发展