Given a linked list, determine if it has a cycle in it.
O(1)空间要求,用快慢指针,若有环,快慢指针必回相交,这是一个追击问题。
若无空间要求,可以用Hashmap
/**
* Definition of singly-linked-list:
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
bool hasCycle(ListNode * head) {
if (head == NULL) {
return false;
}
ListNode * slow = head, * fast = head->next;
while (fast != NULL && fast->next != NULL) {
if (slow == fast) {
return true;
}
slow = slow->next;
fast = fast->next->next;
}
return false;
}
};