一、题目内容

image.png

二、题解

解法1:

思路

a+x = nr = (n-1)r + r= (n-1)r + L - a
a = (n-1)r + L-a-x
L-a-x = 相遇到环入口

代码

  1. public class Solution {
  2. /**
  3. * a+x = nr = (n-1)*r + r= (n-1)*r + L - a
  4. * a = (n-1)r + L-a-x
  5. * L-a-x = 相遇到环入口
  6. *
  7. * @param pHead
  8. * @return
  9. */
  10. public ListNode EntryNodeOfLoop(ListNode pHead) {
  11. if (pHead == null) {
  12. return null;
  13. }
  14. ListNode fast = pHead, slow = pHead;
  15. while (fast != null && fast.next != null) {
  16. fast = fast.next.next;
  17. slow = slow.next;
  18. //相遇
  19. if (fast == slow) {
  20. ListNode slow2 = pHead;
  21. while (slow2 != slow) {
  22. slow2 = slow2.next;
  23. slow = slow.next;
  24. }
  25. return slow;
  26. }
  27. }
  28. return null;
  29. }
  30. }

解法2:

思路

在相遇点断开,就变成了求两个链表相交节点

代码

  1. public ListNode EntryNodeOfLoop(ListNode pHead) {
  2. if (pHead == null || pHead.next == null) {
  3. return null;
  4. }
  5. ListNode fast = pHead, slow = pHead;
  6. while (fast != null && fast.next != null) {
  7. slow = slow.next;
  8. fast = fast.next.next;
  9. if (fast == slow) {
  10. ListNode pHead2 = slow.next;
  11. slow.next = null;
  12. ListNode temp1 = pHead, temp2 = pHead2;
  13. while (temp1 != temp2) {
  14. temp1 = temp1 == null ? pHead2 : temp1.next;
  15. temp2 = temp2 == null ? pHead : temp2.next;
  16. }
  17. return temp1;
  18. }
  19. }
  20. return null;
  21. }