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?

复习时读一个这个链接:http://www.cnblogs.com/hiddenfox/p/3408931.html

遇到的错,在fast和slow相遇后,head从起点走起时,while循环条件一开始我写成了 head != slow,经过验证,head和slow不可能同时走到环的起点,head走到环起点比slow从第一次slow fast相遇点走到环入口要少一步,如果算上dummy到head的那一步,那两者便是相等的,这个和上面链接讲的不一样。

/**
 * 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) {
        if(head == null || head.next == null){
            return null;
        }
        
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        
        ListNode slow = dummy, fast = dummy;
        
        while(fast != null && fast.next != null){
            slow = slow.next;
            fast = fast.next.next;
            
            if(slow == fast){
                break; 
            }
        }
        
        if(fast == null || fast.next == null) return null;
        
        
        while(head != slow.next){
            head = head.next;
            slow = slow.next;
        }
                
        return head;

    }
}

Last updated