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

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

相关推荐
zhuyasen6 小时前
踩坑实录:Go 1.25.x 编译的 exe 在 Windows 提示“此应用无法运行”
windows·golang
Lris-KK7 小时前
力扣Hot100--94.二叉树的中序遍历、144.二叉树的前序遍历、145.二叉树的后序遍历
python·算法·leetcode
千歌叹尽执夏7 小时前
ubuntu24.04lts和Windows11家庭版远程桌面连接若干问题(解决)
windows·远程连接·xrdp·ubuntu24.04lts
坚持编程的菜鸟8 小时前
LeetCode每日一题——螺旋矩阵
c语言·算法·leetcode·矩阵
(●—●)橘子……8 小时前
记力扣2009:使数组连续的最少操作数 练习理解
数据结构·python·算法·leetcode
GalaxyPokemon8 小时前
LeetCode - 1171.
算法·leetcode·链表
iナナ8 小时前
Java优选算法——位运算
java·数据结构·算法·leetcode
Han.miracle9 小时前
数据结构二叉树——层序遍历&& 扩展二叉树的左视图
java·数据结构·算法·leetcode
L_090712 小时前
【Algorithm】Day-4
c++·算法·leetcode
代码充电宝12 小时前
LeetCode 算法题【简单】20. 有效的括号
java·算法·leetcode·面试·职场和发展