赞
踩
背景:在编写判断单链表是否有环时,出现这错误,
错误出现原因: 因为试图使用空指针。
解决方法:增加判断条件,排除对空指针的引用。(一定要注意,我一直以为我排除了所有空指针的情况,其实并没有)
下面是报错的样例程序:
/**
* 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;
while (slow!=NULL && fast->next != NULL)
{
//if (slow == NULL || fast->next == NULL)
// return false;
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
};
下面是修正过后的正确样例,区别在于while中的判断条件
,此时判断条件排除了所有的空指针情况
/**
* 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;
while (slow!=NULL && fast !=NULL &&fast->next != NULL)
{
//if (slow == NULL || fast->next == NULL)
// return false;
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
};
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。