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

这里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 }

 

posted on 2018-03-01 14:27  mayinmiao  阅读(96)  评论(0编辑  收藏  举报