LeetCode 141 Linked List Cycle

用快慢指针来判定是否有环。

这里while loop里的条件,用的是fast.next != null && fast.next.next != null,保证如果没有环,slow一定在中点。

 1 public class Solution {
 2     public boolean hasCycle(ListNode head) {
 3         if (head == null || head.next == null) {
 4                 return false;
 5         }
 6         ListNode fast = head;
 7         ListNode slow = head;
 8         while (fast.next != null && fast.next.next != null) {
 9             slow = slow.next;
10             fast = fast.next.next;
11             if (fast == slow) {
12                 return true;
13             }
14         }
15         return false;
16     }
17 }
原文地址:https://www.cnblogs.com/mayinmiao/p/8488245.html