题目描述

给一个链表,若其中包含环,请找出该链表的环的入口结点,否则,输出null

  1. /*
  2. public class ListNode {
  3. int val;
  4. ListNode next = null;
  5. ListNode(int val) {
  6. this.val = val;
  7. }
  8. }
  9. */
  10. public class Solution {
  11. public ListNode EntryNodeOfLoop(ListNode pHead) {
  12. if (pHead == null) {
  13. return pHead;
  14. }
  15. ListNode fast = pHead;
  16. ListNode slow = pHead;
  17. boolean isExist = false;
  18. while (slow.next != null && fast.next.next != null) {
  19. slow = slow.next;
  20. fast = fast.next.next;
  21. if (slow == fast) {
  22. isExist = true;
  23. break;
  24. }
  25. }
  26. if (isExist) {
  27. slow = pHead;
  28. while (slow != null && fast != null) {
  29. if (slow == fast) {
  30. return slow;
  31. }
  32. slow = slow.next;
  33. fast = fast.next;
  34. }
  35. }
  36. return null;
  37. }
  38. }

引用

https://blog.csdn.net/sinat_35261315/article/details/79205157?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.channel_param