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?

 

Code:

class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *p=head;
        ListNode *cur=head;
        while(p){
            if(p->next)
                p=p->next->next;
            else
                return NULL;
            cur=cur->next;
            if(p==cur)
                return findSpot(head,p);
        }
        return NULL;
    }
ListNode
*findSpot(ListNode *head,ListNode *p){ while(head!=p){ head=head->next; p=p->next; } return head; } };

 

posted @ 2013-11-01 05:45  WinsCoder  阅读(144)  评论(0编辑  收藏  举报