Skip to content

Latest commit

 

History

History
51 lines (35 loc) · 856 Bytes

0141._linked_list_cycle.md

File metadata and controls

51 lines (35 loc) · 856 Bytes

141. Linked List Cycle

难度: Easy

刷题内容

原题连接

内容描述

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;
    }
}