/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; */ class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { unordered_map<ListNode*, int> hash; int i = 0; while (pHead != NULL) { if (hash.find(pHead) != hash.end()) { return pHead; } else { hash[pHead] = i; pHead = pHead->next; i++; } } return pHead; } };
用哈希表从前往后一个个记录结点,当发现有重复的结点时,则说明有环且该结点就是环的入口;当指针=null时,则说明没有环。
哈希表虽然查找起来很方便,但构建表时需要消耗额外的内存空间,这里空间复杂度是O(n),不符合题目要求。但我只能想到这个了。。。