两种解法,一种是通过hash将访问过的存储起来,当遇到环的时候,break; 另一种是快慢指针,floyd解法。
下面是hash_map解法:
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_map<ListNode *, int> all;
int pos(-1), count(0);
while(head != NULL){
if(!all.count(head))
all.insert({{head, count}});
else{
pos = count;
break;
}
head = head->next;
count++;
}
return head;
}
};
floyd 解法:先找环里面的intersection,再找进入环的地点。
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
//ListNode* dummyHead = new ListNode(0);
//dummyHead->next = head;
int pos(-1);
if(head == NULL || head->next == NULL) return NULL;
//find the intersection location
while(fast != NULL && fast->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(fast == slow) break;
}
//cout << "fast val is:" << fast->val << endl;
if(fast == NULL || slow == NULL || fast != slow) return NULL;
else{
fast = head;
pos = 0;
while(fast != slow){
fast = fast->next;
slow = slow->next;
pos++;
}
}
return fast;
}
};