unordered_set
时间复杂度:$O(n)$
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *entryNodeOfLoop(ListNode *head) {
unordered_set<ListNode*> st;
ListNode* p = head;
while (p && st.find(p) == st.end()) { // set中不包含当前节点
st.insert(p);
p = p->next;
}
return p;
}
};