142. Linked List Cycle II

public class Solution {
    public ListNode detectCycle(ListNode head) {
        ListNode p=head,q=head;
        while(p!=null&&p.next!=null)
        {
            p=p.next.next;
            q=q.next;
            if(p==q)
                break;
        }
        if(p==null||p.next==null)
            return null;
        p=head;
        while(p!=q)
        {
            p=p.next;
            q=q.next;
        }
        return p;
    }
}

  

posted @ 2017-10-10 12:30  Weiyu Wang  阅读(115)  评论(0编辑  收藏  举报