Given a linked list, determine if it has a cycle in it.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
bool hasCycle(ListNode *head) {
ListNode* slowerNode = head;
ListNode* fasterNode = head;
while(slowerNode != NULL && fasterNode != NULL && fasterNode->next != NULL){
slowerNode = slowerNode->next;
fasterNode = fasterNode->next->next;
if(slowerNode == fasterNode){
return true;
}
}
return false;
}
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slowerNode = head;
ListNode fasterNode = head;
while ( slowerNode != null && fasterNode != null && fasterNode.next != null ){
slowerNode = slowerNode.next;
fasterNode = fasterNode.next.next;
if (slowerNode == fasterNode){
return true;
}
}
return false;
}
}