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;
    }
};

 

posted @ 2015-01-24 14:51  雄哼哼  阅读(144)  评论(0编辑  收藏  举报