142. Linked List Cycle II

題目142. Linked List Cycle II

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?

思路:是否存在環,環開始的位置,以及環的長度以及證明,參見LeetCode單鏈表(LinkList)總結

public class Solution {
    public ListNode detectCycle(ListNode head) {
         if(head == null){
            return null;
        }
        
        ListNode lowerNode = head;
        ListNode fastNode = head;
        while(lowerNode != null && fastNode != null){
            if(fastNode.next == null){
                return null;
            }
            fastNode = fastNode.next.next;
            lowerNode = lowerNode.next;
            if(lowerNode == fastNode){
                fastNode = head;
                while(lowerNode != fastNode){
                    lowerNode = lowerNode.next;
                    fastNode = fastNode.next;
                }
                return lowerNode;
            }
        }
        return null;
    }
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容