001 - 判断链表是否有环

/**
* 使用快慢指针.如果有环,快指针一定会和慢指针重叠。
*/
public class Solution {
    public boolean hasCycle(ListNode head) {
      if(head == null){
        return false;
      }
       ListNode slow=head;
       ListNode fast=head.next; 
       while(fast!=null && fast.next!=null){
           if(fast!=slow){
               fast=fast.next.next;
               slow=slow.next;
           }else{
               return true;
           }
       } 
       return false;
    }
}
posted @ 2021-03-15 13:09  羽绒333  阅读(39)  评论(0编辑  收藏  举报