Linked List Cycle
Link: https://leetcode.com/problems/linked-list-cycle/
Constraints:
Idea
Using the two pointers technique, slow and fast would point to the same node if there's a node. Otherwise, fast pointers reaches null before the slow pointer.
Code
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}
Similar problem:
- Linked List Cycle II: https://leetcode.com/problems/linked-list-cycle-ii/