Last active
October 17, 2016 02:11
-
-
Save kartikkukreja/961a1449883ac1d753ed51cf2cb97e2b to your computer and use it in GitHub Desktop.
Detecting a cycle in a linked list with a hashset
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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