142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?
/**
* 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) {
// 1.找到环中的任意一个节点
ListNode* oneNode = oneNodeInCycle(head);
if(oneNode == NULL)
return NULL;
// 2.计算环的长度
int len = 1;
ListNode* temp = oneNode;
while(oneNode->next != temp){
++len;
oneNode = oneNode->next;
}
// 3.让fast指针先行len步
ListNode* fast = head;
ListNode* slow = head;
while(len--){
fast = fast->next;
}
// 4.fast和slow指针下次相遇的节点就是入口节点
while(fast != slow){
fast = fast->next;
slow = slow->next;
}
return fast;
}
// 如果有环,返回环中一个节点
// 如果没有环,返回NULL
ListNode* oneNodeInCycle(ListNode* head){
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
return fast;
}
return NULL;
}
};