142. Linked List Cycle II

来源:互联网 发布:网络营销策划案 汽车 编辑:程序博客网 时间:2024/04/28 08:05
class Solution {public:    ListNode *hasCycle(ListNode *head) {        if(!head || !head->next) return NULL;        ListNode *p1 = head, *p2 = head;        while(p1 && p2){            p1 = p1->next;            if(p2->next == NULL)                return NULL;            p2 = p2->next->next;            if(p1 == p2) return p1;        }        return NULL;    }    ListNode *detectCycle(ListNode *head) {        ListNode *p = hasCycle(head);        if(!p) return NULL;        ListNode *s = head;        while(s != p){            s = s->next;            p = p->next;        }        return s;    }};

原创粉丝点击