Skip to content

Instantly share code, notes, and snippets.

@kartikkukreja
Last active October 17, 2016 02:11
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 kartikkukreja/961a1449883ac1d753ed51cf2cb97e2b to your computer and use it in GitHub Desktop.
Save kartikkukreja/961a1449883ac1d753ed51cf2cb97e2b to your computer and use it in GitHub Desktop.
Detecting a cycle in a linked list with a hashset
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* detectCycle(ListNode* A) {
unordered_set<ListNode*> seen;
for (ListNode* i = A; i != NULL; i = i->next) {
if (seen.find(i) != seen.end())
return i;
seen.insert(i);
}
return NULL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment