leecode第一百四十一题(环形链表)

/**
 * 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)
            return false;
        
        ListNode *fast_node=head;
        ListNode *slow_node=head;
        do
        {
            if(slow_node->next!=NULL)//慢指针,一次挪一位
                slow_node=slow_node->next;
            else
                return false;
            
            if(fast_node->next!=NULL)//快指针,一次挪两位
                fast_node=fast_node->next;
            else
                return false;
            if(fast_node->next!=NULL)//懒的想花里胡哨的方法了
                fast_node=fast_node->next;
            else
                return false;
            
        }while(slow_node!=fast_node);//只要有环一定会有两个指针相遇的情况
        
        return true;
    }
};

分析:

这个题我也见过,也是剑指offer上的,但是我错了两处,一是忘了边界处理,二是快指针设置不应该依赖慢指针,应该只看自己的。

原文地址:https://www.cnblogs.com/CJT-blog/p/10669409.html