题解 | 链表中环的入口结点
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution
{
public:
// 哈希法count函数,如果在set容器里面找到了传参的元素,返回1,否则返回0
ListNode* EntryNodeOfLoop(ListNode* head)
{
unordered_set<ListNode*> hash;
while(head!=nullptr)
{
// 进入循环先查找!这样才能确保返回环的入口!
if(hash.count(head)) return head;// 有就返回
// 没有就插入元素,往后遍历!
hash.insert(head);
head=head->next;
}
return nullptr;
}
};