一,Linked List Cycle
题目描述
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull
.
我的代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
/**
* http://www.cnblogs.com/hiddenfox/p/3408931.html
* 重点是看它里面的方法三,介绍的结论。相似的问题有:
* 1,如果有环,求环的长度。
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
if(head == NULL || head->next == NULL){
return NULL;
}
ListNode* fast = head;
ListNode* slow = head;
while(fast->next != NULL && fast->next->next != NULL){
slow = slow->next;
fast = fast->next->next;
if(slow == fast){
slow = head;
while(slow != fast){
slow = slow->next;
fast = fast->next;
}
return slow;
}
}
return NULL;
}
};