首页 > 代码库 > Linked List Cycle II

Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

 

Hash表解法,代码:

class Solution {public:    ListNode *detectCycle(ListNode *head) {        if(head==NULL) return NULL;        if(head->next==NULL) return NULL;        if(head->next==head) return head;        map<ListNode*,bool> m;        ListNode *p=head;        ListNode *res=NULL;        while (p!=NULL)        {            if(m.count(p)==0){m[p]=true;p=p->next;}            else {res=p;break;}        }        return res;    }};

 

Linked List Cycle II