https://leetcode-cn.com/problems/linked-list-cycle/solution/

快慢指针

  1. public boolean hasCycle(ListNode head) {
  2. if (head == null) {
  3. return false;
  4. }
  5. ListNode fast = head.next;
  6. ListNode slow = head;
  7. while (fast != slow) {
  8. if (fast == null || fast.next == null) {
  9. return false;
  10. }
  11. fast = fast.next.next;
  12. slow = slow.next;
  13. }
  14. return true;
  15. }

若还要你返回第一个入环的节点的话,那就在它们相遇时,slow停在原地, fast回到原点,变成两个都一次走一步,那么它俩一定会在第一个入环节点相遇

  1. public ListNode getFirstLoopNode(ListNode head) {
  2. if (head == null || head.next == null || head.next.next == null) {
  3. return null;
  4. }
  5. ListNode fast = head.next;
  6. ListNode slow = head;
  7. while (fast != slow) {
  8. if (fast == null || fast.next == null) {
  9. return null;
  10. }
  11. fast = fast.next.next;
  12. slow = slow.next;
  13. }
  14. fast = head;
  15. while (slow != fast) {
  16. slow = slow.next;
  17. fast = fast.next;
  18. }
  19. return slow;
  20. }