Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
The basic idea of how to determine the cycle inside a linked list is to set 2 pointers looping thru the list,
one pointer should be faster than the other, so that if there is a loop, the faster one may ‘catch’ the slower one smh.
So we loop thru one pointer in step of 2, and the other in step of 1.
And if the next pointer of the node is null, we are sure there will be no loop.
/**
* 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) {
if(head==null) return false;
ListNode faster = head, slower = head;
while(slower!=null&&faster!=null){
if(faster.next==null) return false;
else faster = faster.next.next;
slower = slower.next;
if(faster==slower) return true;
}
return false;
}
}