算法-找出链表环的入口节点

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
核心思路(其实就是佛罗伊德算法): 先根据快慢指针算法找到快慢指针能相遇的最短路程差。
      然后重置快慢指针
      先让快指针走上面得到的路程差
     在让快慢指针一起走,当慢指针和快指针相遇时即是环的入口位置

    
*/ public class Solution { public ListNode detectCycle(ListNode head) { // 如果链表为空或者单节点无环,直接返回null if(head == null || head.next == null){ return null; } // 快慢指针,借鉴是否有环的算法找出来两者能相遇的最小路程差:stepCount ListNode slow = head; ListNode fast = head.next; int stepCount = 0; while(fast != slow){ if(fast == null || fast.next == null){ return null; } fast = fast.next.next; slow = slow.next; stepCount ++; } slow = head; fast = head.next; // fast先走路程差 for(int i = 0; i < stepCount; i ++){ fast = fast.next; } // 当slow和fast相遇时即是环的开始位置 while(fast != slow){ slow = slow.next; fast = fast.next; } return slow; } }

 

posted @ 2020-05-29 09:35  Birding  阅读(260)  评论(0编辑  收藏  举报