141. 环形链表

铭记:

源码下载

141. 环形链表

代码


    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) {
            return false;
        }
        ListNode slow = head;
        ListNode fast = head.next;
        while (slow != null && fast != null) {
            if (slow == fast) {
                return true;
            }
            // 每次循环慢指针走1步
            slow = slow.next;
            // 每次循环快指针走2步
            if (fast.next != null) {
                fast = fast.next.next;
            }
            else {
                fast = null;
            }
        }
        return false;
    }

你可能感兴趣的:(141. 环形链表)