https://leetcode-cn.com/problems/linked-list-cycle/
使用快慢指针:操场上一个跑的慢和一个跑的慢的,两个人终究会相遇
/**
* 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 || head.next==null){
return false;
}
//慢指针
ListNode slow = head;
//快指针
ListNode fast = head.next;
while(fast!=null && fast.next!=null){
if(slow==fast){
return true;
}
//慢指针走一步
slow = slow.next;
//快指针走两步
fast = fast.next.next;
}
return false;
}
}