参考:
代码:
/**
* 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) {
if(head == NULL|| head->next == NULL ||
head->next->next == NULL)
return NULL;
ListNode* fast, *slow;
fast = head;slow = head;
fast = fast->next->next;
slow = slow->next;
while(fast != slow){
//这里要先判断再后移 例如三个节点的单链表就会出错
if(fast == NULL || fast->next == NULL){
return NULL;
}
fast = fast->next->next;
slow = slow->next;
}
ListNode* index = head;
while(index != fast){
index = index->next;
fast = fast->next;
}
return index;
}
};
141. 环形链表 (阉割版)
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fast, *slow;
if(!head||!head->next||!head->next->next)
return false;
fast = head->next->next;slow = head->next;
while(fast != slow){
if(!fast->next||!fast->next->next)
return false;
fast = fast->next->next;
slow = slow->next;
}
return true;
}
};