双指针快慢指针算法细节细说

一开始看到这道经典的老题目,判断是否有环,以为可以直接过去了。
错误提示是:runtime error: member access within null pointer of type ‘ListNode’ (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior
意即访问了空指针。注意到此题中,为了使得每次快指针比慢指针快一个,所以指针二每次跳两个,这时候就有可能造成,指针二先跳到尾巴,这个时候就是链表尾部了,应该直接return false,另一种情况是,指针二跳到了尾节点的前一个节点,这时候如果不跳出的话,下一次直接跳两个直接到了空,于是报错。
所以或表达式应当是两个条件。防止跳到空之后接着跳两个。

/**
 * 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==nullptr||head->next==nullptr) return false;
        ListNode* one=head;
        ListNode* two=head->next;
        while(one!=two){
    
    
            if(two==nullptr||two->next==nullptr){
    
    
                return false;
            }
            one=one->next;
            two=two->next->next;
        }
        return true;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_47741017/article/details/108982033
今日推荐