首页 > 代码库 > Linked List Cycle II

Linked List Cycle 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?

解题方案:

假设循环节点距离头节点距离为L,那么当快指针和慢指针第一次相遇时,快指针和慢指针走的距离分别是K1, K2,则:

K1 = 2K2, K1 - K2 = (S - L)的整数倍,那么K2 = S - L。

下面让慢指针回到头节点,快指针不动,则快慢指针距离循环结点的距离都是L,所以当快慢节点每次都增加1的时候,相遇点就是循环点。下面是该题代码:

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

 

Linked List Cycle II