给一个长度为n链表,若个中包含环,请找出该链表的环的入口结点,否则,返回null。
解析
环很大在前面我们提到过快慢指针,判断是否有环。
代码
package mid.JZ23链表中环的入口结点;class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; }}public class Solution { public ListNode EntryNodeOfLoop(ListNode pHead) { ListNode slow = hasCycle(pHead); if (slow == null) return null; //快的回到出发点 ListNode fast = pHead; while(fast != slow) { fast = fast.next; slow = slow.next; } return fast; } / 判断链表是否有环 @param head @return / public ListNode hasCycle(ListNode head) { if (head == null) return null; ListNode fast = head; ListNode slow = head; while(fast != null && fast.next != null) { //快的走两步 fast = fast.next.next; //慢的走一步 slow = slow.next; //如果相同返回慢的指针 if (fast == slow) return slow; } return null; }}
