I am writing a piece of code for some students and I came up with the following implementation of Floyd's algorithm for finding cycles in linked lists.
I was wondering if there are ways I can improve what I have so far such that the result is
- more C++ idiomatic
- does not contain dumb mistakes associated with the generic code
template <typename T>
struct Node {
T val;
Node* next;
Node() = default;
Node(T x)
: val(x)
, next(nullptr)
{
}
};
template <typename T>
Node<T>* detect_cycle_constant_time(Node<T>* head)
{
Node<T> *n1, *n2;
n1 = n2 = head;
while (n1 && n2) {
n1 = n1->next;
n2 = n2->next;
if (n2)
n2 = n2->next;
else
break;
if (n1 == n2)
break;
}
// second phase of Floyds's algorithm
if (n1 == n2) {
n2 = head;
while (n1 != n2) {
n1 = n1->next;
n2 = n2->next;
}
return n1;
}
return nullptr;
}