Linked List Cycle II, Leetcode 解题笔记

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,然后两个指针同时一步一步前进,直到再次重合,这个重合点就是环开始的位置。

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s