summaryrefslogtreecommitdiff
path: root/top-interview-questions/easy/linked_list/06_linked_list_cycle.cc
blob: e8b4d1d1d90e9d4efc3b60aad4a064fdf6d97962 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
/**
 * 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)       return false;
        if (!head->next) return false;

        const ListNode* next1 = head;
        const ListNode* next2 = head;

        do {
            next1 = next1->next;
            next2 = next2->next;
            if (next2) {
                next2 = next2->next;
            }
        }
        while ((next1 != head) && next1 && next2 && (next1 != next2));

        return next1 && next2 && (next1 == next2);
    }
};