141. 环形链表

2019-08-08  本文已影响0人  一只小星_

给定一个链表,判断链表中是否有环。

 public boolean hasCycle(ListNode head) {
          if (head == null || head.next == null){
            return false;
        }
        //如果head next指向自己,next不是null,也有环
        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;
    }
上一篇下一篇

猜你喜欢

热点阅读