【leetcode】-141-环形链表-判断是否有环

【方法一:快慢指针】

快指针走两步,慢指针走一步,相对于慢指针来说,快指针会在环中一步一步追赶满指针,既然是一步一步追赶,一定会在环中相遇(实际上会在慢指针的第一圈相遇)。如果不会相遇,说明没有环

bool hasCycle(ListNode *head) {
        ListNode *fast=head,*slow=head;
        while(fast!=NULL&&fast->next!=NULL)
        {

            fast=fast->next->next;
            slow=slow->next;

            if(fast==slow) 
                return true;
        }
    
        return false;
    }

猜你喜欢

转载自blog.csdn.net/qq_39328436/article/details/113729861