题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
/* struct ListNode { int val; struct ListNode *next; ListNode(int x) : val(x), next(NULL) { } }; */ class Solution { public: ListNode* EntryNodeOfLoop(ListNode* pHead) { unordered_set<ListNode*> hashset; while( !hashset.count(pHead) && pHead!=nullptr){ //当pHead不在hash里面的时候 hashset.insert(pHead); pHead = pHead->next; } //若无环,则pHead为null输出,若有环,则在该处跳出循环,依旧是pHead return pHead; } };
用hash的方式处理,用空间换时间。因此空间复杂度为n,并不是1,虽然通过但并不满足要求。