[leetCode]141.环形链表

在这里插入图片描述

哈希表

遍历链表,将链表结点依次加入集合,如果集合中已经出现过该结点则说明是环形链表

public class Solution {
    public boolean hasCycle(ListNode head) {
        HashSet set = new HashSet();
        while(head!=null){
            if(!set.contains(head)) set.add(head);
            else return true;
            head=head.next;
        }
        return false;
    }
}

双指针

设置一个快指针和一个慢指针,快指针每次走两步,慢指针每次一步,想象一个圆形赛道,快指针始终会追上慢指针,如果相遇了则是环形链表,如果未相遇则快指针先到终点(fast==null 或 fast.next == null)

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;
    }
}
原文地址:https://www.cnblogs.com/PythonFCG/p/13860000.html