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?

思路:

这道题的难点在于返回cycle begins,我们之前用快慢指针能够确认他是否有cycle,但是如何返回初始点呢?网上找到了一个比较容易理解的解释:

When fast and slow meet at point p, the length they have run are ‘a+2b+c’ and ‘a+b’.
Since the fast is 2 times faster than the slow. So a+2b+c == 2(a+b), then we get ‘a==c’.

142. Linked List Cycle II - 142. Linked List Cycle II

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

喜欢的话订阅一个呗~第一时间收到文章更新哟~

发表评论

电子邮件地址不会被公开。