Created
November 18, 2014 07:23
-
-
Save chuchao333/d7c2ac139aeed66b143d 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) { | |
auto p1 = head; | |
auto p2 = head; | |
// Loop Invariant: | |
while (p1 != NULL && p2 != NULL && p2->next != NULL) { | |
p1 = p1 -> next; | |
p2 = p2 -> next -> next; | |
if (p1 == p2) | |
return true; | |
} | |
return false; | |
} | |
}; | |
// Note: | |
// 1. Don't miss the 'p2 != NULL' in the while condition |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment