leetcode 第141题:环形列表

leetcode

第141题:环形列表

第一种:哈希列表

public boolean hasCycle(ListNode head) {
        Set<ListNode> seen = new HashSet<ListNode>();
        while (head != null) {
            if (seen.contains(head)) {
                return true;
            }
            seen.add(head);
            head = head.next;
        }
        return false;
    }

第二种:快慢指针:

快指针走两步,慢指针走一步,相遇则说明有环

if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != fast) {
            if (fast == null || fast.next == null) {
                return false;
            }
            slow = slow.next;
            fast = fast.next.next;
        }
        return true;
    }


posted @ 2024-02-05 15:23  米乡卷炸粉  阅读(9)  评论(0)    收藏  举报