cpp
/*
给一个长度为n链表,若其中包含环,请找出该链表的环的入口结点,否则,返回null。
*/
#include <bits/stdc++.h>
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
//哈希表
/* class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
unordered_set<ListNode*> mySet;
while (pHead)
{
if(mySet.find(pHead) == mySet.end())
{
mySet.insert(pHead);
pHead = pHead->next;
}
else
{
return pHead;
}
}
return nullptr;
}
}; */
//双指针
class Solution {
public:
ListNode* EntryNodeOfLoop(ListNode* pHead) {
ListNode* slow = pHead;
ListNode* fast = pHead;
bool frist = true;
while (slow != fast || frist)
{
frist = false;
slow = slow->next;
if(!slow) return nullptr;
fast = fast->next;
if(!fast) return nullptr;
fast = fast->next;
if(!fast) return nullptr;
}
fast = pHead;
while (slow != fast)
{
slow = slow->next;
fast = fast->next;
}
return slow;
}
};
int main()
{
return 1;
}
golang
/*
给一个长度为n链表,若其中包含环,请找出该链表的环的入口结点,否则,返回null。
*/
package main
func EntryNodeOfLoop(pHead *ListNode) *ListNode {
map_node := make(map[*ListNode]bool, 0)
for pHead != nil {
if _, ok := map_node[pHead]; !ok {
map_node[pHead] = true
pHead = pHead.Next
}else{
return pHead
}
}
return nil
}