这里可以使用使用unordered_set,避免排序;当我们迭代链表是,当一次查找这个地址,发现set中有,那么我们判断这里有环;
/**
* 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) {
unordered_set<ListNode*> m;
while (head) {
if (m.find(head) != m.end()) return true;
m.insert(head);
head = head->next;
}
return false;
}
};