LeetCode - 141. 环形链表

141. 环形链表

import java.util.Objects;

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) {
        val = x;
        next = null;
    }
}
public class Solution {
    public boolean hasCycle(ListNode head) {

        if (Objects.isNull(head) || Objects.isNull(head.next)) {
            return false;
        }

        ListNode slow = head;
        ListNode fast = head.next.next;

        while (Objects.nonNull(fast)) {
            if (slow == fast) {
                return true;
            }

            slow = slow.next;
            
            if (Objects.isNull(fast.next)) {
                return false;
            }

            fast = fast.next.next;
        }

        return false;

    }
}


猜你喜欢

转载自blog.51cto.com/tianyiya/2287470