給定一個(gè)鏈表,判斷它是否有環(huán)。
思路:
快指針每次走兩步
慢指針每次走一步
走到最后如果兩指針相遇表示有環(huán),若快指針走到最后為空,則沒(méi)有環(huán)
/**
* 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 ;
}
};