出错代码:
/*使用代码为leetcode141-环形链表*/
/**
* 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||!head->next) return false;
ListNode *slow=head,*fast=head->next;
while(slow!=fast){
if(!slow||!fast){/*这一步出错了*/
return false;
}
slow=slow->next;
fast=fast->next->next;
}
return true;
}
};
出错位置:
if(!slow||!fast){/*这一步出错了*/
原因:
fast=fast->next->next;
当fast->next为空时,上面该语句实际是fast=null->next,对当前这样的fast进行判空操作if(!slow||!fast)时就出错了。
/**
* 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||!head->next) return false;
ListNode *slow=head,*fast=head->next;
while(slow!=fast){
if(!slow||!fast||!fast->next){/*添加一个对fast->next的判空就可以了*/
return false;
}
slow=slow->next;
fast=fast->next->next;
}
return true;
}
};