给定一个链表,判断它是否有环。
思路:
快指针每次走两步
慢指针每次走一步
走到最后如果两指针相遇表示有环,若快指针走到最后为空,则没有环
/**
* Definition of ListNode
* 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) {
// write your code here
if (!head || !head->next) {
return false;
}
ListNode *fast = head->next;
ListNode *slow = head;
while(fast && slow) {
if(fast == slow) {
return true;
} else {
fast = fast->next;
if(fast) {
fast = fast->next;
slow = slow->next;
} else {
return false;
}
}
}
return false ;
}
};