Open wupangyen opened 3 years ago
use two pointer method
one slow one fast
slow starts at head fast starts at head. next
loop through when slow != fast is true inside the loop slow = slow.next , fast = fast.next.next, fast is two node before slow. also we need to check the case when we loop through every node in the linked list, when fast and fast.next == null, it means there is no cycle in the linked list.
we exit the loop when slow == fast it means we find a match and there is a cycle
public class Solution { public boolean hasCycle(ListNode head) { // the case when the linked list is empty if(head == null) { return false; } ListNode slow = head; ListNode fast = head.next;
while(slow != fast ){
/* fast.next == null is the edge case when
linked list only have two element prevent
fast = fast.next.next have null pointer
exception */
/*
fast == null
edge case when linked list length is one
*/
if(fast == null || fast.next == null){
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}
Time O(n) number of nodes in linked list Space O(1) didn't allocate extra space
Given head, the head of a linked list, determine if the linked list has a cycle in it.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. Note that pos is not passed as a parameter.
Return true if there is a cycle in the linked list. Otherwise, return false.
Example: Input: head = [3,2,0,-4], pos = 1 Output: true Explanation: There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).