题目描述
思路分析
链表+哈希表
一个哈希表对地址判重即可。
还有一种巧妙的做法,只用 O ( 1 ) O(1) O(1)空间
代码实现
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
unordered_map<ListNode*,bool> hash;
ListNode* EntryNodeOfLoop(ListNode* head) {
auto p=head;
while(p&&!hash[p]) hash[p]=true,p=p->next;
return p;
}
};
class Solution {
public:
ListNode *entryNodeOfLoop(ListNode *head) {
if (!head || !head->next) return 0;
ListNode *first = head, *second = head;
while (first && second)
{
first = first->next;
second = second->next;
if (second) second = second->next;
else return 0;
if (first == second)
{
first = head;
while (first != second)
{
first = first->next;
second = second->next;
}
return first;
}
}
return 0;
}
};