题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
#include <cstddef>
#include <set>
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
ListNode* cur = pHead;
std::set<ListNode*> haxi;
while (cur->next!=NULL) {
if(haxi.count(cur)>0){
return cur;
}
haxi.insert(cur);
cur = cur->next;
}
return NULL;
}
};
哈希表:遍历列表时,建立一个集合来保存节点指针,直到读取一个节点两次的时候,判断集合中已存在此节点,则此节点为环入口
SHEIN希音公司福利 222人发布