要记住这样的写法,如果head为空或者单结点,直接false。如果不是就把慢指针设为head,快指针设为head->next,防止一开始直接相等。while结束的条件就是他俩相等,内部先判断快指针是否为null或者快指针的下一个是否为null,这很重要,很容易出错,这里只要判断快的,因为五环的话快的一定先走完。最后返回true
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
//链表=空间鲁棒性
if(head == NULL || head->next == NULL) return false;
//这两个赋初值必须这样来,不然直接进不去循环了
ListNode* slow = head;
ListNode* fast = head->next;
while(slow != fast){
//如果无环,也一定是fast先走到null
//循环结束的条件就是slow=fast
if(fast == NULL || fast->next == NULL) return false;
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
//链表=快慢指针+空间鲁棒性
//如果head为空或者head下一个为空就是false
if(head == NULL || head->next == NULL) return false;
ListNode* fast = head->next;
ListNode* slow = head;
//如果等于就退出循环并返回true,如果在途中fast走到null了就返回false
while(fast != slow){
if(fast == NULL || fast->next == NULL) return false;
fast = fast->next->next;
slow = slow->next;
}
return true;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
//快慢指针即可
if(head == NULL || head->next == NULL) return false;
ListNode* slow = head, *fast = head->next;
while(slow != fast){
if(fast == NULL || fast->next == NULL) return false;
slow = slow->next;
fast = fast->next->next;
}
return true;
}
};