linked list cycle c++
class Solution {
public:
bool hasCycle(ListNode *head) {
unordered_set<ListNode*> visited;
if (head == NULL) {
return false;
}
while (head) {
if (visited.count(head)) {
return true; // has appeared before
}
visited.insert(head);
head = head->next;
}
return false;
}
};