leetcode142 Linked List Cycle II

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

Note: Do not modify the linked list.

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        ListNode *p1=head;
        ListNode *p2=head;
        if(!p1)
            return NULL;
        
        do{
            p1=p1->next;
            p2=p2->next;
            if(p2)
                p2=p2->next;
        }while(p1&&p2&&p1!=p2);
        if(!p1||!p2)
            return NULL;
        p1=head;
        while(p1!=p2)
        {
            p1=p1->next;
            p2=p2->next;
        }
        return p1;
    }
};

note:

开始时,两指针都指向head,之后再快步慢步走;

假设head为A,环起始点为B,两指针相遇点为C,则LAB=LBC+n环周长;

 

posted @ 2016-05-09 19:01  西小贝  阅读(154)  评论(0编辑  收藏  举报