Linked List Cycle II

来源:互联网 发布:淘宝刷手兼职怎么做 编辑:程序博客网 时间:2024/05/21 11:31

原理在linked list cycle 中已经叙述过了 这里不再叙述

class Solution {public:   ListNode *detectCycle(ListNode *head) {        ListNode *fast=head;        ListNode *slow=head;        if(!head)            return false;        bool hascycle=false;        while(slow&&fast&&fast->next)        {            slow=slow->next;            fast=fast->next->next;            if(slow==fast)            {                hascycle=true;                break;            }        }       if(!hascycle)           return NULL;       else       {           ListNode *temp=head;           while(1)           {               if(temp==slow)                   break;               temp=temp->next;               slow=slow->next;           }           return slow;       }    }};
0 0
原创粉丝点击