This file contains hidden or 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: | |
// Two pointer technique | |
bool hasCycle(ListNode *head) { | |
if(!head) return false; | |
auto slow = head; | |
auto fast = head; | |
while(slow->next and fast->next and fast->next->next){ | |
slow = slow->next; | |
fast = fast->next->next; | |
if(slow == fast) return true; | |
} | |
return false; | |
} | |
}; |
No comments:
Post a Comment