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;
}
};
142. Linked List Cycle II
最新推荐文章于 2022-05-19 13:04:17 发布
