# Linked List Cycle

Problem I:

Given a linked list, determine if it has a cycle in it.

Problem 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?

(1) 相遇的地点一定在环路上；

(2) 相遇时，慢指针一定在环路上走了小于等于一圈；

(3) 假设慢指针需要k步走到环路的起点，相遇时慢指针走了m步，那么快指针走了2m步，且相遇点是在偏离环路起点m-k的位置（0≤m-k<n，其中n为环路的节点数），并且m = λn。

k + x = m

k + (x + λn) = 2m

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

posted @ 2014-04-29 20:17  夏目家的猫咪老师  阅读(335)  评论(0编辑  收藏  举报