兩種解法,一種是通過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;
}
};