Skip to content

Latest commit

 

History

History
33 lines (25 loc) · 787 Bytes

快慢指针.md

File metadata and controls

33 lines (25 loc) · 787 Bytes

快慢指针

代码如下:

class Solution {
public:
    bool hasCycle(ListNode *head) 
    {
        if(head == nullptr || head -> next == nullptr)
            return false;
        ListNode *fast , *slow;
        slow = head;
        fast = head -> next;
        while(fast != slow)
        {
            if(fast == nullptr || fast -> next == nullptr)
                return false;
            
            slow = slow -> next;
            fast = fast -> next -> next;
        }

        return true;
    }
};

设置两个指针一个指针每次指向下一个位置,另一个指针指向下下个位置,如果链表中存在环,则两个指针一定会相等,否则则不会相等