1. public class Solution {
    2. public ListNode detectCycle(ListNode head) {
    3. //如果没有长度或者长度是1自然不是环
    4. if(head == null || head.next == null){
    5. return null;
    6. }
    7. ListNode slow = head;
    8. ListNode fast = head.next;
    9. while(slow != fast){
    10. if(fast == null || fast.next == null){
    11. return null;
    12. }
    13. slow = slow.next;
    14. fast = fast.next.next;
    15. }
    16. //slow 继续走,fast从head开始重新走,每次走一步直到两个相遇
    17. fast = head;
    18. while (slow != fast){
    19. slow = slow.next;
    20. fast = fast.next;
    21. }
    22. fast = head;
    23. while (slow != fast) {
    24. slow = slow.next;
    25. fast = fast.next;
    26. }
    27. return fast;
    28. }
    29. }