题目链接
    image.png

    1. /**
    2. * Definition for singly-linked list.
    3. * class ListNode {
    4. * int val;
    5. * ListNode next;
    6. * ListNode(int x) {
    7. * val = x;
    8. * next = null;
    9. * }
    10. * }
    11. */
    12. public class Solution {
    13. // 时间复杂度O(1), 空间复杂度O(N),s随着链表的变长而变长
    14. public boolean hasCycle2(ListNode head) {
    15. Set<ListNode> set = new HashSet<>();
    16. while(head != null) {
    17. if(!set.add(head)) { // 添加不进去说明有环。
    18. return true;
    19. }
    20. head = head.next;
    21. }
    22. return false;
    23. }
    24. // 我写的快慢指针。
    25. public boolean hasCycle(ListNode head) {
    26. if(head == null) return false;
    27. // 使用双指针
    28. ListNode low = head;
    29. ListNode high = head;
    30. while(high.next != null && high.next.next != null) {
    31. low = low.next;
    32. high = high.next.next;
    33. if(low == high) return true;
    34. }
    35. return false;
    36. }
    37. // 老师的快慢指针
    38. public boolean hasCycle3(ListNode head) {
    39. if(head == null) {
    40. return false;
    41. }
    42. ListNode slow = head;
    43. ListNode quick = head.next; // head已经进行处理,不会为空了
    44. while(slow != quick) {
    45. if(quick == null || quick.next == null) return false;
    46. slow = slow.next;
    47. quick = quick.next.next; // quick.next在前面已经处理了,不会为null
    48. }
    49. return true;
    50. }
    51. }