smilevchy's blog

Life & Study & Chasing

Leetcode_Linked List Cycle

原题链接: https://oj.leetcode.com/problems/linked-list-cycle/

public boolean hasCycle(ListNode head) {
    if (head == null) return false;

    ListNode slowCursor = head;
    ListNode quickCursor = head;

    while (quickCursor.next != null && quickCursor.next.next != null) {
        slowCursor = slowCursor.next;
        quickCursor = quickCursor.next.next;

        if (slowCursor != null && quickCursor != null && (quickCursor == slowCursor || quickCursor.next == slowCursor)) {
            return true;
        }
    }

    return false;
}

algorithm

« Leetcode_Single Number Trap of '0.1 + 0.2' »