题解 | #哈希表——链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
/*使用哈希表unorder_map判断链表是否有环,若有环返回入口点*/
#include <unordered_set>
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
unordered_set<ListNode *> s;
while (pHead) {
if(s.count(pHead) == 1) return pHead;
else s.insert(pHead);
pHead = pHead->next;
}
return nullptr;
}
};
查看16道真题和解析