Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
public boolean hasCycle(ListNode head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(null == head){
return false;
}
ListNode first = head;
ListNode second = head;
while(first.next != null && first.next.next !=null){
if(first.next.equals(second) || first.next.next.equals(second)){
return true;
}
first = first.next.next;
second = second.next;
}
if(first.next != null && first.next.equals(second)){
return true;
}
return false;
}