Description Link to heading

141.linked-list-cycle

Solution Link to heading

We can use two pointers, one fast, one slow. For each time, fast move to next next node, slow move to next node. If there is cycle, fast will be equal to slow, or fast will be nullptr.

Code Link to heading

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