public boolean hasCycle(ListNode head) {
if (head==null||head.next==null) return false;
ListNode slow = head;
ListNode fast = head.next;
while (fast!=null&&fast.next!=null){
slow = slow.next;
fast = fast.next.next;
if(fast==slow) return true;
}
return false;
}
判断一个链表是否有环:快慢指针(个人理解:其实就是追赶问题)
- 设置两个指针,一快一慢
- fast指针走两步,slow指针走一步
- 如果相遇,说明有环
- 如果fast== null或fast.next==null说明链表遍历到了尽头,即没环