Skip to content

141. Linked List Cycle

难度: Easy

刷题内容

原题连接

  • https://leetcode.com/problems/linked-list-cycle

内容描述

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

Follow up:
Can you solve it without using extra space?

解题方案

思路 1 **- 时间复杂度: O(N)*- 空间复杂度: O(1)***

快慢指针

java
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null){
            return false;
        }
        ListNode fast = head;
        ListNode slow = head;
        while (fast != null && slow != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if (slow == fast){
                return true;
            }
        }
        return false;
    }
}

我们一直在努力

apachecn/AiLearning

【布客】中文翻译组