Problem:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null
.
Solution:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
unordered_map<ListNode*, int> map;
while(head && map.find(head) == map.end()){
map[head];
head = head->next;
}
return head;
}
};