LeetCode-Linked List Cycle II -有环链表-推理
https://oj.leetcode.com/problems/linked-list-cycle-ii/
在判断成环问题的基础上需要做一些推理才能得到简洁的解法。
首先,假设环的起点距离head有m步。则当p到达起点时,q的位置在环上的m%n处。那么p,q相遇的位置相对于起点就是(n-m%n),在这个位置再走m步,则恰好到达起点。而如果p回到头部,走m步,也恰好到达这个点。那么简单的解法就得到了。
需要对m=0的情况也做考虑,这样最开始p=head->next。q=head->next->next。即可。
/** * 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) { if(head==NULL) return NULL; ListNode *p=head->next; if(p==NULL) return NULL; ListNode *q=NULL; if (p->next==NULL) return NULL; q=p->next; while(p!=NULL &&q!=NULL){ if(p==q) break; p=p->next; q=q->next; if(q!=NULL) q=q->next; else return NULL; } if(p!=q) return NULL; p=head; while(p!=q) { p=p->next; q=q->next; } return p; } };