代码改变世界

Linked List Cycle II

2015-04-07 15:59  笨笨的老兔子  阅读(151)  评论(0编辑  收藏  举报

给定一个链表,如果该链表有环,请返回环的起点,否则返回NULL

思路:一个FAST每次前进两步和一个SLOW每次前进一步,当两个指针相等的时候,其中一个回到head,然后两个同时往前走,再次相遇时的位置就是环的起点
证明:
假设第一次相遇时,SLOW走了M步,FAST走了2M步,环的长度是L,相遇点距离环的起点为K,则此时FAST回到起点,距离环的起点为M-K,SLOW距离环的起点为L-K,当FAST走完M-K到达环的起点时,SLOW走了λL+LK,两者一定在起点处相遇。

  1. class Solution {
  2. public:
  3. ListNode *detectCycle(ListNode *head) {
  4. if (head)
  5. {
  6. ListNode* fast = head;
  7. ListNode* slow = head;
  8. while (fast->next != NULL)
  9. {
  10. slow = slow->next;
  11. fast = fast->next->next;
  12. if (fast == NULL )
  13. {
  14. return NULL;
  15. }
  16. if (fast == slow)
  17. {
  18. fast = head;
  19. while (fast != slow)
  20. {
  21. fast = fast->next;
  22. slow = slow->next;
  23. }
  24. return fast;
  25. }
  26. }
  27. }
  28. return NULL;
  29. }
  30. };