1. 程式人生 > 其它 >連結串列中環的入口結點--LeetCode第142題

連結串列中環的入口結點--LeetCode第142題

技術標籤:LeetCode

給一個連結串列,若其中包含環,請找出該連結串列的環的入口結點,否則,輸出null。

題解:

  • 快慢指標法,快指標一次走兩步,慢指標一次走一步,當快慢指標第一次相遇,此時: 2(x+y)=n圈周長+x+y
  • 相遇以後快指標回到head和慢指標以同樣速度每次走一步,最終會在連結串列中環的入口結點處相遇。
    這裡可以這樣理解, x + y = n圈周長, y = n圈周長 - x; 快慢指標再繼續走x後, 快指標走到入口點,此時慢指標再圓中走的路程為: x + y, 剛好為圓n圈周長。
package com.alibaba.study.tiba;

import com.
alibaba.fastjson.JSON; import com.alibaba.study.utils.ListNode; /** * @Auther: wjj * @Date: 2021/1/12 16:06 * @Description: */ public class LeetCode142 { public ListNode detectCycle(ListNode head) { if(head == null || head.next == null || head.next.next ==null){ return null;
} ListNode slow = head; ListNode fast = head.next.next; while (slow != fast){ if(slow == null || fast == null || fast.next == null){ return null; } slow = slow.next; fast = fast.next.next; } fast =
head; while (fast != slow){ fast = fast.next; slow = slow.next; } return fast; } }