JAVA-Linked List Cycle I&&Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Follow up:
Can you solve it without using extra space?

 
第一題要求是否有環 從圖中可以看出 使用快慢指針 只要有環兩者必定會相遇  另外從相遇點可以看出 相遇點距離環的起始點的距離與head到起始點的距離是相同的 只要再設一指針 與slow一起走 相遇點即環的起始點 
 若設 環的大小爲 a 快慢指針的路程分別爲x和y   則  x+a=y , y=2x  ==>x=a;即慢指針走過的路程恰爲環的大小  此時從相遇點到環起點恰爲整個鏈表的長度 而從head出發恰好差一個環的距離 所以相遇點必爲環的起點 代碼如下:
public class Solution {
    public ListNode detectCycle(ListNode head) {
        if(head==null||head.next==null) return null;
        ListNode slow=head;
        ListNode fast=head;
        int count=0;
        while(fast.next!=null&&fast.next.next!=null){
            slow=slow.next;
            fast=fast.next.next;
            count++;
            if(slow==fast)  break;
        }
        if(slow==fast&&count!=0){
            ListNode res=head;
            while(res!=slow){
                res=res.next;
                slow=slow.next;
            }
            return res;
        }else{
            return null;
        }
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章