给定一个链表,判断链表中是否有环。
思路:双指针法
定义快慢指针,慢指针一次走一步,快指针一次走两步,若快指针走到末尾还没有遇见慢指针,则链表没有环。
public boolean hasCycle(ListNode head) {
if(head == null || head.next == null) return null;
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast) return true;
}
return false;
}