leetcode-141-easy

Linked List Cycle
思路一: 用 set 记录每个节点的 hashCode,如果遇到重复,说明是循环

public boolean hasCycle(ListNode head) {
    Set<Integer> set = new HashSet<>();
    while (head != null) {

        if (set.contains(head.hashCode())) {
            return true;
        }
        set.add(head.hashCode());

        head = head.next;
    }

    return false;
}

思路二: 快慢指针,一个每次进一步,一个每次进两步,如果是循环链表,他们一定会相遇

public boolean hasCycle(ListNode head) {
    ListNode h1 = head;
    ListNode h2 = head;

    while (h2 != null) {
        h2 = h2.next;
        if (h2 == null) return false;
        h2 = h2.next;
        h1 = h1.next;

        if (h2 == h1) return true;
    }

    return false;
}
posted @ 2022-10-19 07:33  iyiluo  阅读(19)  评论(0)    收藏  举报