Skip to content

Instantly share code, notes, and snippets.

@mach-kernel
Created August 11, 2015 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mach-kernel/604039b0989f63a6ffe0 to your computer and use it in GitHub Desktop.
Save mach-kernel/604039b0989f63a6ffe0 to your computer and use it in GitHub Desktop.
/**
* 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) {
if (!head) return NULL;
map<ListNode*, int> nodes = map<ListNode*, int>();
while (head->next) {
try {
if (nodes.at(head->next) == 0) return head->next;
}
catch (out_of_range o) {
nodes.insert(pair<ListNode*, int>(head, 0));
head = head->next;
}
}
return NULL;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment