Skip to content

Instantly share code, notes, and snippets.

@chuchao333
Created November 18, 2014 07:23
Show Gist options
  • Save chuchao333/d7c2ac139aeed66b143d to your computer and use it in GitHub Desktop.
Save chuchao333/d7c2ac139aeed66b143d to your computer and use it in GitHub Desktop.
Linked List Cycle
/**
* 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