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:

posted on 2021-08-08 12:11  blackraven25  阅读(22)  评论(0编辑  收藏  举报