142. 环形链表 II

给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null

  1. public ListNode detectCycle(ListNode head) {
  2. if (head == null) {
  3. return null;
  4. }
  5. ListNode slow = head, fast = head;
  6. while (fast != null) {
  7. slow = slow.next;
  8. if (fast.next != null) {
  9. fast = fast.next.next;
  10. } else {
  11. return null;
  12. }
  13. if (fast == slow) {
  14. ListNode ptr = head;
  15. while (ptr != slow) {
  16. ptr = ptr.next;
  17. slow = slow.next;
  18. }
  19. return ptr;
  20. }
  21. }
  22. return null;
  23. }
  24. 作者:LeetCode-Solution
  25. 链接:https://leetcode-cn.com/problems/linked-list-cycle-ii/solution/huan-xing-lian-biao-ii-by-leetcode-solution/