Created
July 6, 2017 02:39
-
-
Save restart916/6c2c9ad5a9f9564493891a65c02e5176 to your computer and use it in GitHub Desktop.
Linked List Cycle
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) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
bool hasCycle(ListNode *head) { | |
ListNode *start = head; | |
ListNode *curr = start; | |
// printf("%x\n", start); | |
if (curr == 0) return false; | |
if (curr->next == 0) return false; | |
if (curr->next == start) return true; | |
curr = curr->next; | |
while(curr->next) { | |
if (curr->next == curr) return true; | |
ListNode *checker = start; | |
while(checker != curr) { | |
// printf("%x %x\n", checker, curr->next); | |
if(checker == curr->next) { | |
return true; | |
} | |
checker = checker->next; | |
} | |
curr = curr->next; | |
} | |
return false; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment