题解 | #链表中环的入口结点#
链表中环的入口结点
https://www.nowcoder.com/practice/253d2c59ec3e4bc68da16833f79a38e4
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
#include <map>
class Solution {
public:
//判断当前节点是否被遍历过
bool IS_EXIST(map<int,ListNode*>& listMap,ListNode* cur){
for(auto lm : listMap){
if(cur == lm.second) return true;
}
return false;
}
ListNode* EntryNodeOfLoop(ListNode* pHead) {
//记录当前节点
ListNode* cur = pHead;
//用来存储遍历过的节点
map<int,ListNode*> listMap;
int i = 0;
while(cur){
if(IS_EXIST(listMap, cur)) return cur;
listMap.insert(make_pair(i, cur));
i++;
cur = cur->next;
}
return nullptr;
}
};
查看9道真题和解析