O
问题
实现
思路
判断有环采用快慢指针去走。 快指针一次走两次, 慢指针一次走一个格子,如果有环那么一定是会相遇的,相遇的时候就是退出的时候。
- define fast , slow
- while(fast!&&fast.next!==NULL)
-
- fast = fast +2
-
- slow = slow +1
-
- if(fast ==slow ) return true
- return false;
总结与反思
- 注意考虑next.next 如何保证不越界。
代码实现
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while(fast && fast->next){
// make sure next is not null that make next.next is not null.
fast = fast->next->next;
slow = slow->next;
if(fast == slow ) return true;
}
return false;
}
};