Created
October 30, 2015 19:17
-
-
Save mengdiwang/1d5850b217aedf4e886d 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) { | |
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