- 思路
之前学习过快慢指针法,可用于判断循环或求中位数,于是用在这里
快指针每次走两步,慢指针每次走一步,若不存在环,则不会相遇,若存在必定会相遇 - 贴上代码,此版本执行时间较短
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
bool hasCycle(struct ListNode *head) {
if(head == NULL || head->next == NULL)
return false;
struct ListNode *slow = head;
struct ListNode *fast = head;
fast = fast->next->next;
slow = slow->next;
while(1){
if(fast == NULL || fast->next == NULL)
return false;
else if(fast == slow || fast->next == slow)
return true;
else{
fast = fast->next->next;
slow = slow->next;
}
}
}