141. 环形链表

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

  • 哈希指针
public static boolean hasCycle(ListNode head) {
    Set set = new HashSet<>();
    while (head!=null){
        if(!set.add(head)){
            return true;
        }
        head=head.next;
    }
    return true;
}
  • 快慢指针
public class Solution {
    public boolean hasCycle(ListNode head) {
        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;
    }
}

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