Leetcode 题目解析之 Linked List Cycle

2022-01-14 11:36:29 浏览数 (1)

Given a linked list, determine if it has a cycle in it.

Follow up:

Can you solve it without using extra space?

快慢指针,定义两个指针,一个每次走一步,另一个每次走两步。如果快指针“遇到”了慢指针,说明有环。

代码语言:javascript复制
    public boolean hasCycle(ListNode head) {

        if (head == null) {
            return false;
        }

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

        while (fast != null) {

            if (fast.next == null || fast.next.next == null) {
                return false;
            }

            if (slow == fast) {
                return true;
            }

            fast = fast.next.next;
            slow = slow.next;
        }

        return false;
    }

0 人点赞