141. Linked List Cycle

来源:互联网 发布:淘宝产品模板详情代码 编辑:程序博客网 时间:2024/06/08 19:10

这里写图片描述
这里写图片描述
快慢指针的应用。慢指针每次一步,快指针每次两步。要是有环的话终究是要相遇的。

    bool hasCycle(ListNode *head) {        ListNode*slow=head,*fast=head;        if(!head) return false;        while(fast){            slow=slow->next;            fast=fast->next;            if(fast)                fast=fast->next;            else return false;            if(fast==slow)                return true;        }        return false;    }
    bool hasCycle(ListNode *head) {        ListNode*slow=head,*fast=head;              while(fast&&fast->next){            slow=slow->next;            fast=fast->next->next;                      if(fast==slow)                return true;        }        return false;    }
    bool hasCycle(ListNode *head) {        ListNode*slow=head,*fast=head;              while(fast&&fast->next&&fast->next->next){            slow=slow->next;            fast=fast->next->next->next;                      if(fast==slow)                return true;        }        return false;    }

跑的快的终极是要追上跑的慢的,理想情况下,快的是慢的2倍时,当慢的跑完一次全程,快的已经跑完2次的全程。

原创粉丝点击