Skip to content

Instantly share code, notes, and snippets.

@mengdiwang
Created October 30, 2015 19:17
Show Gist options
  • Save mengdiwang/1d5850b217aedf4e886d to your computer and use it in GitHub Desktop.
Save mengdiwang/1d5850b217aedf4e886d 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) {
if(head == NULL)
return false;
ListNode *step1 = head;
if(step1->next == NULL)
return false;
ListNode *step2 = step1->next;
while(step1!=NULL && step2!=NULL)
{
if(step1 == step2)
return true;
if(step1->next != NULL)
step1 = step1->next;
if(step2->next == NULL)
return false;
else
step2 = step2->next->next;
}
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment