Leetcode题库 141.环形链表

Leetcode题库 141.环形链表,第1张

文章目录
  • 思路
  • 代码

思路

one_step指针每轮循环向前走一步
double_step指针每轮循环向前走两步
double_step指针速度快于double_step指针
double_step指针判断前面两步是否为null,若为空则说明无环形
再判断前面两步是否与one_step指针相逢,若相逢说明有环形

代码
bool hasCycle(struct ListNode *head) {
    if(head==NULL) return false;
    struct ListNode *one_step=head,*double_step=head->next;
    bool ret = false;
    while(1){
        if(double_step==NULL || double_step->next==NULL) break;
        if(double_step==one_step || double_step->next==one_step){ ret=true;break;}

        one_step = one_step->next;
        double_step = double_step->next->next;
    }
    return ret;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/565020.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-06
下一篇 2022-04-06

发表评论

登录后才能评论

评论列表(0条)

保存