141. 环形链表
设置一个fast指针,一个slow指针,fast一次走两步,slow一次走一步。如果fast和slow相遇,则说明有环。反之没相遇则无环。
注意快慢指针的while循环条件是fast.next != null && fast.next.next != null
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null) return false;
ListNode fast = head, slow = head;
while(fast.next!=null && fast.next.next!=null){
fast = fast.next.next;
slow = slow.next;
if(fast == slow) return true;
}
return false;
}
}